const fs = require('fs');
const chalk = require('chalk');
const inquirer = require('inquirer');

const generators = fs
  .readdirSync(`${__dirname}/generators`)
  .filter(f => !f.startsWith('.'))
  .map(f => {
    return {
      name: `${f.padEnd(15)} - ${chalk.gray(require(`./generators/${f}/meta.json`).description)}`,
      value: f,
      short: f,
    };
  });

const runGenerator = async (generatorPath) => {
    return new Promise(resolve => {
        const name = ''
        const cwd = process.cwd()

        const Generator = require(generatorPath);
        const generator = new Generator({
            name,
            env: {
                cwd,
            },
            resolved: require.resolve(generatorPath),
        });

        return generator.run(() => {
            console.log('✨ File Generate Done');
            resolve(true);
        });
    });
};


const run = async () => {
    process.send && process.send({ type: 'prompt' });
    process.emit('message', { type: 'prompt' });
    const answers = await inquirer.prompt([
        {
            name: 'type',
            message: '选择项目模板：',
            type: 'list',
            choices: generators,
        },
    ]);
    try {
        return runGenerator(`./generators/${answers.type}`);
    } catch(e) {
        console.error(chalk.red(`> Generate failed`), e);
        process.exit(1);
    }
    
};

module.exports = run;