#! /usr/bin/env node

const sh = require('shelljs');
const commandLineArgs = require('command-line-args');
const path = require('path');
const chalk = require('chalk');
const promptForBucket = require('./functions/promptForBucket');
const promptForTarget = require('./functions/promptForTarget');
const confirmDestination = require('./functions/confirmDestination');
const loadCertSettings = require('./functions/loadCertSettings');
const updateUrlsToStaging = require('./functions/updateUrlsToStaging');
const extractResourcesAndReplaceUrls = require('./functions/extractResourcesAndReplaceUrls');
const initOfflineConfig = require('./functions/initOfflineConfig');
const checkScriptsUpToDate = require('./functions/checkScriptsUpToDate');
const releaseLegacy = require('./functions/releaseLegacy');

const rootPath = __dirname.split('node_modules')[0];
const packagePath = path.join(rootPath, 'package.json');
const pkg = require(packagePath);

const buckets = (pkg && pkg.config && pkg.config.aws && pkg.config.aws.buckets) ||
  ['dev-apps.enplug.in', 'apps.enplug.in', 'apps.enplug.com'];

const optionDefinitions = [
  { name: 'build-for-release', alias: 'r', type: Boolean },
  { name: 'dev-server', alias: 's', type: Boolean },
  { name: 'dev', alias: 'd', type: Boolean },
  { name: 'target', alias: 't', type: String },
  { name: 'targets', type: String, multiple: true},
  { name: 'version', alias: 'v', type: String }
];

const options = commandLineArgs(optionDefinitions);
const version = options.dev ? pkg.version_dev : pkg.version;
const destination = options.dev ? `${pkg.config.destination}/dev` : pkg.config.destination;

let target = options['target']; // app or dashboard
let targets = options.targets ? options.targets : ['app', 'dashboard'];
let bucket = ''; // s3 bucket apps.enplug.in or apps.enplug.com

/**
 * Copies offline support service woker over to the application.
 */
function copyOfflineSupportWorker() {
  return new Promise((resolve) => {
    try {
      const commonStaticResources = [
        '.',
        './',
        './index.html',
        './enplug-offline-worker.js'
      ];
      let indexFilePath = path.join(rootPath, 'dist/app/index.html');
      let configPath = path.join(rootPath, 'offline.config.json');
      let srcFilePath = path.join(__dirname, './templates/enplug-offline-worker.js');
      let destFilePath = path.join(rootPath, 'dist/app/enplug-offline-worker.js');
      
      let offlineConfig = initOfflineConfig(require(configPath), pkg, commonStaticResources);
      
      extractResourcesAndReplaceUrls(offlineConfig, pkg, indexFilePath, srcFilePath, [destFilePath])
        .then(resolve);
    } catch (e) {
      console.warn(`Unable to copy offline support service worker. Please check whether ${chalk.default.cyan('offline.config.json')} exists.`);
      resolve();
    }
  });
}

function runBuild() {
  const needsDevServer = options['dev-server'];
  let command = '';

  if (needsDevServer) {
    const devCert = loadCertSettings(rootPath);
    // webpack server + selected target + dev config
    command = `webpack-dev-server --https --config webpack.config.${target}.dev.js --watch --colors --inline --progress --host localhost.enplug.in --cert "${devCert.cert}" --key "${devCert.key}"`;
  } else {
    command = 'rimraf dist/' + target + // clean previous build
      ' && rimraf tmp ' + // clean tmp
      // webpack build + selected target + prod config
      ' && webpack --https --config webpack.config.' + target + '.prod.js --bail --progress --profile';
  }

  sh.exec(command, function () {
    const fixOfflineSupportWorker = target === 'app' 
      ? copyOfflineSupportWorker()
      : Promise.resolve();

    const fixUrlsToStaging = target === 'app' && bucket.endsWith('enplug.in')
      ? () => updateUrlsToStaging(rootPath, 'dist/app', false)
      : () => Promise.resolve([]);
    
    fixOfflineSupportWorker
      .then(fixUrlsToStaging)
      .then(() => {
        if (!options['build-for-release']) { return; }
        
        let prefix = `${destination}/${target}/${version}`;
        confirmDestination(bucket, prefix).then(function (response) {
          if (response.confirm) {
            return releaseLegacy(pkg, bucket, prefix, target);
          }
        });
      });
  });
}

checkScriptsUpToDate(pkg)
  .then(() => {
    if (options['build-for-release']) {
      promptForBucket(bucket, buckets)
        .then(selectedBucket => bucket = selectedBucket)
        .then(() => promptForTarget(target, targets))
        .then(selectedTarget => target = selectedTarget)
        .then(runBuild);
    } else {
      promptForTarget(target, targets)
        .then(selectedTarget => target = selectedTarget)
        .then(runBuild);
    }
  })
  .catch((err) => {
    console.error('BUILD ERROR:')
    console.error(`${err}`);
  })





