#! /usr/bin/env node

'use strict';

const commandLineArgs = require('command-line-args');
const path = require('path');
const chalk = require('chalk');
const shell = require('shelljs');
const rootPath = __dirname.split('node_modules')[0];
const pkg = require(path.join(rootPath, 'package.json'));
const updateUrlsToStaging = require('./functions/updateUrlsToStaging');
const promptForBucket = require('./functions/promptForBucket');
const confirmDestination = require('./functions/confirmDestination');
const syncDist = require('./functions/syncDist');
const buildAngular = require('./functions/buildAngular');

let bucket;

// Parse inline arguments
const optionDefinitions = [
  { name: 'bucket', alias: 'b', type: String },
  { name: 'configuration', type: String },
  { name: 'ignoreversion', type: Boolean },
  { name: 'nooffline', type: Boolean },
  { name: 'prefix', alias: 'p', type: String },
  { name: 'root', alias: 'r', type: String },
  { name: 'target', alias: 't', type: String },
  { name: 'test', type: Boolean },
  { name: 'version', alias: 'v', type: String },
  { name: 'webplayer', type: Boolean},
  { name: 'electron', type: Boolean },
];
const options = commandLineArgs(optionDefinitions);
const destination = pkg.config.destination;
const version = pkg.version;

function runBuild() {
  console.log(`\n${chalk.default.greenBright('Building Angular project')}\n`);

  buildAngular(pkg, options, destination, version).then(function () {
    var fixUrlsToStaging = bucket.endsWith('enplug.in')
      ? updateUrlsToStaging(rootPath, 'dist', options.nooffline)
      : Promise.resolve([]);

    fixUrlsToStaging.then(function () {
      if (options.test) {
        shell.exec('npm test');
      }
      let prefix = path.posix.join(destination, version);
      if (options.ignoreversion) {
        prefix = destination;
      }
      confirmDestination(bucket, prefix).then(function (response) {
        if (response.confirm) {
          syncDist(pkg, bucket, prefix, 'dist/');
        }
      });
    });
  }).catch(error => {
    console.error(`${chalk.default.red('BUILD ERROR')}`)
    console.error(error);
  });
}

promptForBucket(bucket, pkg.config.aws.buckets)
  .then(selectedBucket => bucket = selectedBucket)
  .then(runBuild);
