const chalk = require('chalk');
const childProcess = require('child_process');
const execSync = childProcess.execSync;
const cli = require('./cli');
const build = require('./build');
const postBuild = require('./post-build');
const install = require('./install');
const path = require('path');
const utils = require('./utils');

const appGenerate = (options) => {
  if (options.inputConfig) {
    console.info(chalk.cyan('Creating your project - automated mode : \n'));
  } else {
    console.info(chalk.cyan('Configuring your project : please answer the following : \n'));
  }

  // Query the questions
  // -------------------
  return cli.start(options)
    .then((config) => {
      // Storing config
      // --------------
      const cliConfig = config;
      // Building the file structure
      // ---------------------------
      return build.start({
        config: config,
        targetPath: options.targetPath
      })
      // Post build operations
      // ---------------------
      .then(() => {
        return postBuild.start({
          config: cliConfig,
          targetPath: options.targetPath
        });
      })
      // Install dependencies
      // --------------------
      .then(() => {
        return install.start({
          config: cliConfig,
          targetPath: options.targetPath,
        });
      })
      // starting app
      .then(() => {
        if (!cliConfig.appStart || typeof cliConfig.npmInstall !== 'boolean' || !cliConfig.npmInstall) {
          return;
        }
        console.log('');
        console.log('');
        console.log('*****************************************************************');
        console.log(chalk.cyan(' Starting eUI app... browser will open soon on localhost:4200'));
        console.log('*****************************************************************');

        const wd = path.resolve(utils.getAngularPath(options.targetPath, cliConfig.appName, cliConfig.appType, cliConfig.artifactId));
        return execSync("npm start", { cwd: wd, stdio: "inherit" });
      })
    })
    .catch((e) => {
      console.error(e);
      process.exitCode = 1;
    })
    .finally(() => process.exit())
}


module.exports = {
  appGenerate,
};
