#!/usr/bin/env node
var Liftoff = require('liftoff');
var argv = require('minimist')(process.argv.slice(2));
var path = require('path');
var settings = require('../conf/settings');
var fs = require('fs');
var readlineSync = require('@fsteam/readline-sync');
var hoo = require('../');

// register global variable
Object.defineProperty(global, 'hoo', {
  enumerable: true,
  writable: false,
  value: hoo
});

var prePromise = Promise.resolve();
var project_title;
var cli = new Liftoff({
  name: 'hoo', // 命令名字
  processTitle: 'hoo',
  moduleName: 'hoo',
  configName: 'hoo-conf',
  // only js supported!
  extensions: {
    '.js': null
  }
});

var user_path = argv._[1];
if (user_path === undefined) {
  user_path = '.';
}

/*项目初始化*/
if (argv._[0] === 'init') {
  require('../lib/init');
  return;
}

/*SQ工程化的处理*/
var sqCmd = require( '../sqp/config/hoo.cmd' ).cmd;
if ( sqCmd.hasOwnProperty( argv._[ 0 ] ) ) {
  require( '../sqp/index' )[ sqCmd[ argv._[ 0 ] ] ].apply( hoo, argv._ );
  return;
}
/*SQ工程化的处理 结束*/

prePromise = prePromise.then(function(){
  return new Promise(function (resolve) {
    require('../lib/getAvailablePorts')(function(){
      resolve();
    })
  });
});

if (argv._[0] === 'dev' && argv.origin) {
  require('../lib/browserSyncOnly')(user_path, argv.p || argv.port);
  return;
}

//开发活动专题
if ((argv._[0] === 'dev' || argv._[0] === 'prod' || argv._[0] === 'deploy') && argv._.length > 1) {
  argv.r = argv.root = path.join(settings.sourceDir, user_path);
  argv._.pop();
}

//开发官网
if ((argv._[0] === 'wDev' || argv._[0] === 'wProd' || argv._[0] === 'wDeploy') && argv._.length > 1) {
  argv.r = argv.root = path.join(settings.wwwSourceDir, user_path);
  argv._.pop();
}

//图片压缩
if ((argv._[0] === 'pngc' || argv._[0] === 'wpngc') && argv._.length > 1) {
  argv.r = argv.root = path.join(argv._[0] === 'pngc' ? settings.sourceDir : settings.wwwSourceDir, user_path);
  argv._.pop();
}

//提交活动专题源码
if (argv._[0] === 'submit' && argv._.length > 1) {
  argv.r = argv.root = path.join(settings.sourceDir, user_path);
  argv._.pop();
}

/*测试sftp*/
if (argv._[0] === 'sftp' && argv._.length > 1) {
  require('../lib/sftp');
  return;
}

if (argv._[0] === 'deploy' && user_path !== '.') {
  prePromise = prePromise.then(function () {
    return new Promise(function (resolve) {
      if (fs.existsSync(path.join(process.cwd(), settings.sourceDir, user_path))) {
        resolve();
      } else {
        hoo.log.error('不存在的路径，请仔细检查');
      }
    })
  });

  prePromise = prePromise.then(function () {
    return new Promise(function (resolve) {
      require('jsdom').env(
        path.join(process.cwd(), settings.sourceDir, user_path, 'index.html'),
        function (err, window) {
          project_title = readlineSync.question('-------开始分割线-------\n 请输入提交到svn远程仓库的信息（默认读取首页标题:' + window.document.title + '）:', {
            limit: function (input) {
              if (!input) return false;
              if (input.length < 4) return false;
              return true;
            },
            limitMessage: '抱歉, 不得少于4个字符.',
            defaultInput: window.document.title
          });
          resolve();
        }
      )
    })
  });
}

if (argv._[0] === 'wDeploy') {
  prePromise = prePromise.then(function () {
    return new Promise(function (resolve) {
      require('jsdom').env(
        path.join(process.cwd(), settings.wwwSourceDir, user_path, 'index.html'),
        function (err, window) {
          project_title = readlineSync.question('-------开始分割线-------\n 请输入提交到svn远程仓库的信息（默认读取首页标题:' + window.document.title + '）:', {
            limit: function (input) {
              if (!input) return false;
              if (input.length < 4) return false;
              return true;
            },
            limitMessage: '抱歉, 不得少于4个字符.',
            defaultInput: window.document.title
          });
          resolve();
        }
      )
    })
  });
}




prePromise.then(function () {
  cli.launch({
    cwd: argv.r || argv.root,
    configPath: argv.f || argv.file
  }, function (env) {
    env.modulePath = '../';
    /*
     * 日志共6个级别
     * hoo.log.L_ALL
     * hoo.log.L_DEBUG
     * hoo.log.L_ERROR
     * hoo.log.L_NORMAL 默认配置
     * hoo.log.L_NOTIC
     * hoo.log.L_WARNI
     * */

    hoo.log.level = hoo.log.L_NORMAL;

    if (argv.log) {
      hoo.log.level = hoo.log.L_ALL;
      delete  argv.log;
    }

    //选取相应的media配置
    if (argv._[0] === 'dev') {
      process.env.NODE_ENV = "development";
      hoo.log.info('dev------进入开发模式（支持现代浏览器自动同步刷新）------HOO前端工程化');
      require('../conf/hoo_medias/development')(hoo, user_path, argv.p || argv.port);
      argv._.unshift('release');
      argv.w = true;
      // argv.L = true;不使用fis3自带的live-reload 改为使用browser-sync
      delete argv.p;
      delete argv.port;
    } else if (argv._[0] === 'prod') {
      process.env.NODE_ENV = "production";
      hoo.log.info('prod------将上线代码' + path.join(settings.deployDir, user_path) + '自动上传到测试环境------HOO前端工程化');
      require('../conf/hoo_medias/prod')(hoo, user_path, argv.relative);
      argv._.unshift('release');
      argv.w = true;
      argv.L = true;
      argv.c = true;
      delete argv.d;
      delete argv.relative;
    } else if (argv._[0] === 'deploy') {
      process.env.NODE_ENV = "production";
      hoo.log.info('deploy------将上线代码产出到本地，上传到测试环境，并提交svn------HOO前端工程化');
      require('../conf/hoo_medias/deploy')(hoo, user_path, argv.d, argv.relative, project_title);
      delete argv.relative;
      argv._.unshift('release');
    } else if (argv._[0] === 'wDeploy') {
      process.env.NODE_ENV = "production";
      hoo.log.info('deploy------将上线代码产出到本地，上传到测试环境，并提交svn------HOO前端工程化');
      argv.c = true;
      require('../conf/hoo_medias/wDeploy')(hoo, user_path, argv._[0], project_title, argv.source);
      argv._.unshift('release');
    } else if (argv._[0] === 'wDev') {
      process.env.NODE_ENV = "development";
      hoo.log.info('wDev------将官网静态资源产出到本地，调整官网UI');
      argv.w = true;
      // argv.L = true;不使用fis3自带的live-reload 改为使用browser-sync
      require('../conf/hoo_medias/wDev')(hoo, user_path, argv._[0], argv.p || argv.port);
      argv._.unshift('release');
      delete argv.p;
      delete argv.port;
    } else if (argv._[0] === 'wProd') {
      process.env.NODE_ENV = "production";
      hoo.log.info('wProd------将官网js、css、图片资源发布到img1本地目录并自动上传到官网测试环境');
      require('../conf/hoo_medias/wProd')(hoo, user_path, argv._[0], argv.source);
      argv.w = true;
      argv.c = true;
      delete argv.source
      argv._.unshift('release');
    } else if (argv._[0] === 'pngc' || argv._[0] === 'wpngc') {
      process.env.NODE_ENV = "development";
      hoo.log.info('pngc、wpngc------将活动专题/官网png图片进行压缩');
      require('../conf/hoo_medias/pngc')(hoo, user_path, argv._[0]);
      argv._.unshift('release');
    } else if (argv._[0] === 'submit') {
      process.env.NODE_ENV = "development";
      hoo.log.info('submit------将活动专题源代码自动提交至svn库');
      require('../conf/hoo_medias/submit')(hoo, user_path, argv.m);
      argv._.unshift('release');
      delete argv.m;
    } else if (argv._[0] === 'server') {
      // console.log(argv,env);
    } else if (argv.c || argv.clear) {
      argv._.unshift('release');
    } else if (argv.v || argv.version) {

    } else {
      argv = {
        _: [],
        h: true
      }
    }

    // 配置插件查找路径，优先查找本地项目里面的 node_modules
    // 然后才是全局环境下面安装的 hoo 目录里面的 node_modules
    hoo.require.paths.unshift(path.join(env.cwd, 'node_modules'));
    hoo.require.paths.push(path.join(path.dirname(__dirname), 'node_modules'));
    hoo.cli.run(argv, env);
  });
});
