#!/usr/bin/env node

const yParser = require('yargs-parser');
const semver = require('semver');
const chalk = require('chalk');
const ora = require('ora')
const run = require('./lib/run');
const args = yParser(process.argv.slice(2));
const { exec } = require('child_process');
const inquirer = require('inquirer');
const isOnline = require('is-online');
const { name, version } = require('./package.json')


if (args.v || args.version) {
  console.log(version);
  process.exit(0);
}

if (!semver.satisfies(process.version, '>= 8.0.0')) {
  console.error(chalk.red('✘ The generator will only work with Node v8.0.0 and up!'));
  process.exit(1);
}

//检查网络状态
isOnline().then(online => {
  if(online){
    const initSpinner = ora("检查脚手架版本，请稍候...\n");
    const updateSpinner = ora("正在更新脚手架，请稍候...\n");
    initSpinner.start()
    // 检查远程脚手架是否更新版本
    exec(`npm view ${name} version`, (err, stdout, stderr) => {
      if (err){
        console.log(err);
        initSpinner.color = "red";
        initSpinner.fail("版本检测失败！");
      } else {
        // 远程版本与当前版本对比
        if(semver.satisfies(version, `= ${stdout}`)) {
          initSpinner.color = "green";
          initSpinner.succeed('脚手架已是最新版本，创建工程。\n');
          run()
        } else {
          initSpinner.color = "green";
          initSpinner.succeed('脚手架存在新版本。\n');
          inquirer.prompt([{
              type: "confirm",
              message: "是否下载最新版本？",
              name: "isupdate",
          }]).then(answers => {
            const { isupdate } = answers;
            if(isupdate) {
              updateSpinner.start()
              // 更新本地版本
              exec(`npm install ${name} -g`,(err, stdout, stderr) => {
                if (err){
                  updateSpinner.color = "red";
                  updateSpinner.fail("脚手架更新失败！\n");
                } else {
                  updateSpinner.color = "green";
                  updateSpinner.succeed('脚手架更新成功。\n');
                }
              })
            } else {
              run()
            }
          })
        };
      }
    })
  }else{
    run()
  }
});
