const fs = require('fs-extra')
const path = require('path')
const chalk = require('chalk')
const inquirer = require('inquirer')
const Creator = require('./Creator')
const { clearConsole } = require('./util/clearConsole')
const { error, stopSpinner } = require('@vue/cli-shared-utils')

async function generate (model, options) {
  const cwd = options.cwd || process.cwd()
  const targetDir = path.resolve(cwd, model || '.')

  if (fs.existsSync(targetDir)) {
    if (!options.force) {
      await clearConsole(true)

      const { action } = await inquirer.prompt([
        {
          name: 'action',
          type: 'list',
          message: `Target directory for ${chalk.cyan(model)} crud view already exists. Pick an action:`,
          choices: [
            { name: 'Overwrite', value: 'overwrite' },
            { name: 'Cancel', value: false }
          ]
        }
      ])
      if (!action) {
        return
      } else if (action === 'overwrite') {
        console.log(`\nRemoving ${chalk.cyan(model)} crud view...`)
      }
    }
  }

  const creator = new Creator(name, targetDir)
  await creator.generate(options)
}

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