var spawn = require('child_process').spawn;
const path = require('path');
const fs = require('fs');

const writeApiJson = function () {
  /* API Url set by build parameter */
  let apiConfig = {
    "course_api_url": "http://m-xyyf-api.ai160.com/",
    "lesson_api_url": "http://m-xyyf-api.ai160.com/lesson",
    "tts_api_url": "https://yfxxt-api.ai160.com/baidu/accessToken",
    "xiaomi_qr": "https://h5.tv.mi.com/store/thirdparty/pricetag/shortkey/",
    "en": "pro"
  };
  let options = process.argv;
  for (let i = 0; i < options.length; i++) {
    if (options[i].indexOf('-test') == 0) {
      apiConfig = { // 开发环境
        "course_api_url": "http://m-xyyf-api.ai160.com/",
        "lesson_api_url": "http://m-xyyf-api.ai160.com/lesson",
        "tts_api_url": "https://yfxxt-api.ai160.com/baidu/accessToken",
        "xiaomi_qr": "https://h5.tv.mi.com/store/thirdparty/pricetag/shortkey/",
        "en": "test"
      };
    }
  }
  fs.writeFileSync(path.join(__dirname, 'src/res/values/api.json'), JSON.stringify(apiConfig));
  console.log('Write API Config Success!');
}

const writeTimeStamp = function () {
  /* JavaScript and CSS Import TimeStamp set by UnixTimeStamp */
  let ts = Math.floor(new Date().getTime() / 1000);
  let fileStr = fs.readFileSync(path.join(__dirname, 'build/stage/index/index.html')) + '';
  fileStr = fileStr.replace(/\[timestamp\]/g, ts); //时间戳标记替换为时间戳
  fileStr = fileStr.replace(/\/index.js/g, '/index.min.js'); //index.js替换为index.min.js
  fileStr = fileStr.replace(/\/index.css/g, '/index.min.css'); //index.js替换为index.min.js
  fs.writeFileSync(path.join(__dirname, 'build/stage/index/index.html'), fileStr);
  console.log('Write JavaScript and CSS Import TimeStamp = ' + ts + ' Success!');
}

//因为引用在代码里面的json文件，在webpack打包时会直接打在生成后的index.js里面，所以需要在执行moye b 之前，就修改src目录内的api.json
writeApiJson();

//启动
const moyeb = spawn('moye', ['b'], {
  shell: true
});

// 捕获标准输出并将其打印到控制台 
moyeb.stdout.on('data', function (data) {

  let stdoutStr = data.toString();
  if (stdoutStr.indexOf("Finished \'default\' after") >= 0) {
    writeTimeStamp();
    setTimeout(function () {
      console.log('TV Package Build Success!');
      moyeb.kill();
    }, 1000);
  }
});

// 捕获标准错误输出并将其打印到控制台 
moyeb.stderr.on('data', function (data) {
  console.log('' + data);
});

// 注册子进程关闭事件 
moyeb.on('exit', function (code, signal) {
  if (code && code != 0) {
    console.log('Build Error!! Code:' + code);
    return;
  }
  console.log('Build Done!!');
});