const fs = require('fs-extra');
const path = require('path');
const inquirer = require('inquirer');
const Creator = require('./Creator');
const { clearConsole } = require('./util/clearConsole');
const { getPromptModules } = require('./util/createTools');
const chalk = require('chalk');
// const { chalk, error, stopSpinner, exit } = require('@vue/cli-shared-utils');
const validateProjectName = require('validate-npm-package-name');

async function create(projectName, options) {
  // if (options.proxy) {
  //   process.env.HTTP_PROXY = options.proxy;
  // }

  // const cwd = options.cwd || process.cwd();
  const cwd = process.cwd();
  const inCurrent = projectName === '.';
  const name = inCurrent ? path.relative('../', cwd) : projectName;
  const targetDir = path.resolve(cwd, projectName || '.');

  // console.log('name :>> ', name);
  // console.log('targetDir :>> ', targetDir);

  const result = validateProjectName(name);
  if (!result.validForNewPackages) {
    console.error(chalk.red(`Invalid project name: "${name}"`));
    result.errors &&
      result.errors.forEach(err => {
        console.error(chalk.red.dim('Error: ' + err));
      });
    result.warnings &&
      result.warnings.forEach(warn => {
        console.error(chalk.red.dim('Warning: ' + warn));
      });
    process.exit(1);
  }

  // 判断当前要创建的文件夹是否存在
  // if (fs.existsSync(targetDir) && !options.merge) {
  if (fs.existsSync(targetDir)) {
    if (options.force) {
      await fs.remove(targetDir);
    } else {
      await clearConsole();
      if (inCurrent) {
        const { ok } = await inquirer.prompt([
          {
            name: 'ok',
            type: 'confirm',
            message: `Generate project in current directory?`
          }
        ]);
        if (!ok) {
          return;
        }
      } else {
        const { action } = await inquirer.prompt([
          {
            name: 'action',
            type: 'list',
            message: `Target directory ${chalk.cyan(
              targetDir
            )} already exists. Pick an action:`,
            choices: [
              { name: 'Overwrite', value: 'overwrite' },
              { name: 'Merge', value: 'merge' },
              { name: 'Cancel', value: false }
            ]
          }
        ]);
        if (!action) {
          return;
        } else if (action === 'overwrite') {
          console.log(`\nRemoving ${chalk.cyan(targetDir)}...`);
          await fs.remove(targetDir);
        }
      }
    }
  }

  // console.log('开始创建... :>> ', '开始创建...');
  const creator = new Creator(name, targetDir, getPromptModules());
  // const creator = new Creator(name, targetDir, 1);
  await creator.create(options);
}

module.exports = (...args) => {
  create(...args);
  // return create(...args).catch(err => {
  //   stopSpinner(false); // do not persist
  //   error(err);
  //   if (!process.env.VUE_CLI_TEST) {
  //     process.exit(1);
  //   }
  // });
};
