const download = require('download')
const path = require('path')
const rimraf = require('rimraf')
const signale = require('signale')

const {
  detectOS,
  detectOwnVersion,
  detectOwnName,
} = require('./utils');

const buildDownloadInfo = () => {
  // build os label
  const osLabel = detectOS();
  // build version label
  const { version } = detectOwnVersion();
  signale.info('buildDownloadInfo version=', version);

  var name = detectOwnName();
  signale.info('buildDownloadInfo name=', name);

  // generate download url
  return {
    packageVersion: version,
    platform: osLabel,
    downloadUrl: `https://tic-res-1259648581.cos.ap-shanghai.myqcloud.com/${name}/${version}/${name}-${osLabel}-${version}.zip`
  };
};

const main = () => {
  const {
    packageVersion,
    platform,
    downloadUrl
  } = buildDownloadInfo();
  const outputDir = './';
  const removeDir = path.join(__dirname, '../build');
  const removeDir2 = path.join(__dirname, '../liteav');
  // rm dir `build`
  rimraf(removeDir2, err => {
    if (err) {
      signale.fatal(err);
      process.exit(1);
  }});

  rimraf(removeDir, err => {
    if (err) {
      signale.fatal(err);
      process.exit(1);
    }

    // print download info
    signale.info('removeDir  =', removeDir);
    signale.info('outputDir  =', outputDir);

    signale.info('Package Version =', packageVersion);
    signale.info('Platform =', platform);
    signale.info('Download Url =', downloadUrl, '\n');

    // start
    signale.pending('Downloading C++ addon Electron SDK...\n');
    download(downloadUrl, outputDir, {
      strip: 0,
      extract: true
    }).then(() => {
      signale.success('Success', 'Download finished');
    }).catch(err => {
      signale.fatal('Failed', err);
    });
  });
};

main();


