#!/usr/bin/env node
const inquirer = require('inquirer')
const program = require('commander')
const shell = require('shelljs')
const { log, colors } = require('../packages/utils/log')
const { spawn } = require('child_process')
const _ = require('lodash')

const {
  updateConfigs,
  updateCodes,
  updatePackages,
  restoreConfigs,
  restoreLegacyCodes
} = require('../packages/actions')

const BANNER = `
             *                      *
                     .
          |\\___/|
          )     (             .              *
         =\\     /=
           )===(       *
          /     \\
          |     |
         /       \\
         \\       /
  _/\\_/\\_/\\__  _/_/\\_/\\_/\\_/\\_/\\_/\\_/\\_/\\_/\\_
  |  |  |  |( (  |  |  |  |  |  |  |  |  |  |
  |  |  |  | ) ) |  |  |  |  |  |  |  |  |  |
  |  |  |  |(_(  |  |  |  |  |  |  |  |  |  |
  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
`

const VERSION = '1.1.1'

const run = async () => {
  console.info(BANNER)
  // add extra \n for good looking
  console.log('\n')
  log.title('📝  Update config files')
  updateConfigs()
  log.title('💯  Update legacy codes')
  updateCodes()
  const { willUpdatePackages } = await inquirer.prompt([
    {
      name: 'willUpdatePackages',
      type: 'confirm',
      default: true,
      message:
        'Would you like to update packages? It is OK to skip if already updated.'
    }
  ])
  if (willUpdatePackages) {
    log.title('🎁 Update pacakages')
    updatePackages()
  }

  log.title('🐥  Everything set! Run yarn dev now')
  // since shelljs.exec doesn't work with inqurier.js
  // use spawn instead
  spawn('yarn', ['dev'], {
    stdio: 'inherit'
  })
}

program.version(VERSION)

program
  .command('run')
  .description('Run wildcat')
  .action(run)

program
  .command('restore')
  .description('Restore the previous configs and codes.')
  .action(async () => {
    restoreConfigs()
    restoreLegacyCodes()
    const { willRemoveNodemodules } = await inquirer.prompt([
      {
        name: 'willRemoveNodemodules',
        type: 'confirm',
        default: false,
        message: 'Would you like to remove node_modules?'
      }
    ])
    if (willRemoveNodemodules) {
      log.title('📦  Remove node_modules')
      shell.rm('-rf', './node_modules')
    }
  })

program.parse(process.argv)

// default command when no params attached
if (_.isEmpty(program.args)) {
  console.log(BANNER)
  colors.title(`Version: v${VERSION}\n`)
  console.log(
    `  ${colors.title(
      'Wildcat is a cli tool for accelerating webpack dev server of Bobcat.'
    )}`
  )
  program.help()
}
