#! /usr/bin/env node

'use strict';

const commandLineArgs = require('command-line-args');
const path = require('path');

const rootPath = __dirname.split('node_modules')[0];
const packagePath = rootPath + 'package.json';
const pkg = require(packagePath);
const checkForExistingRelease = require('./functions/checkForExistingRelease');
const updateUrlsToStaging = require('./functions/updateUrlsToStaging');
const createS3Client = require('./functions/createS3Client');
const promptForBucket = require('./functions/promptForBucket');
const promiseWrapUploader = require('./functions/promiseWrapUploader');
const confirmDestination = require('./functions/confirmDestination');

let bucket;

// Parse inline arguments
const optionDefinitions = [
  { name: 'bucket', alias: 'b', type: String },
  { name: 'dev', alias: 'd', type: Boolean },
  { name: 'ignoreversion', type: Boolean },
  { name: 'nooffline', type: Boolean },
  { name: 'player', type: Boolean},
  { name: 'prefix', alias: 'p', type: String },
  { name: 'root', alias: 'r', type: String },
  { name: 'target', alias: 't', type: String },
  { name: 'version', alias: 'v', type: String },
];
const options = commandLineArgs(optionDefinitions);

const destination = pkg.config.destination;
const version = pkg.version;


function runBuild() {
  let command = 'enplug-build';
  if (options.dev) { command += ' --dev'; }
  if (options.player) { command += ' --player'; }
  if (options.nooffline) { command += ' --nooffline'; }
  if (options.ignoreversion) { command += ' --ignoreversion'; }
  if (bucket.endsWith('enplug.com')) { command += ' --prod'; }

  console.log(`Running command: ${command}`);
  // shell.exec(command, function (argument) {// todo uncomment
  var fixUrlsToStaging = bucket.endsWith('enplug.in')
    ? updateUrlsToStaging(rootPath, 'dist', options.nooffline)
    : Promise.resolve([]);

  fixUrlsToStaging.then(function () {
    if (!options.dev) {
      // shell.exec('npm test'); // todo uncomment
    }
    let prefix = path.posix.join(destination, version);
    if (options.ignoreversion) {
      prefix = destination;
    }
    confirmDestination(bucket, prefix).then(function (response) {
      if (response.confirm) {
        syncDist(bucket, prefix);
      }
    });
  });
  // });// todo uncomment
}


/**
 *
 * @param {*} bucket
 * @param {*} prefix
 */
function syncDist(bucket, prefix) {
  if (prefix.startsWith('/')) {
    prefix = prefix.substr(1);
  }

  let uploadOptions = {
    localDir: 'dist/',
    deleteRemoved: false, // keep older versions
    s3Params: {
      Bucket: bucket,
      Prefix: prefix,
      // can add options for putObject command
      // see: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property
    }
  };

  let s3Client = createS3Client(pkg, `${rootPath}/../aws.private.json`);

  return checkForExistingRelease(s3Client, bucket, prefix).then(function () {
    console.log('DEPLOY'); return;    // todo remove

    return promiseWrapUploader(s3Client.uploadDir(uploadOptions))
      .catch(function (error) {
        console.error('There was an error during the release process!');
        console.error(error.stack);
        return null;
      })
      .then(function (result) {
        if (result == null) {
          return;
        }
        console.log('Release finished');
      });
  }, () => { });

}


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