#!/usr/bin/env node

/*
	Licensed Material - Property of IBM

	(C) Copyright 2015, 2016 IBM Corp.

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/


var nopt = require('nopt');
var pkg = require('../package.json');
var log = require('npmlog');
var errors = require('mdo-errors');

var opts = nopt({
  version: Boolean,
  debug: Boolean,
  ddebug: Boolean,
  noprompt: Boolean
}, {
  v: '--version',
  d: '--debug',
  dd: '--ddebug'
});

if (opts.debug) {
  global.MDO_CLI_LOG_LEVEL = 'verbose';
}
if (opts.ddebug) {
  global.MDO_CLI_LOG_LEVEL = 'silly';
}

// override the default log level if MDO_CLI_LOG_LEVEL has been set
log.level = global.MDO_CLI_LOG_LEVEL ? global.MDO_CLI_LOG_LEVEL : log.level;

log.heading = pkg.name;
log.verbose('cli', 'process.argv=%j', process.argv);
log.verbose('cli', 'opts=%j', opts);

global.MDO_CLI_NO_PROMPT = opts.noprompt;

var pkg = require('../package.json');
// keep this version information for anyone that may need them separately
global.MDO_CLI_VERSION = pkg.productVersion;  // this allows the package version to be different than the product version
global.MDO_CLI_BUILD_ID = pkg.version.split('.')[2];  // use the 3rd segment of the package version
global.MDO_CLI_FULL_VERSION = global.MDO_CLI_VERSION + '-' + global.MDO_CLI_BUILD_ID;

log.verbose('cli', 'mobilefirst@%s', global.MDO_CLI_VERSION);
log.verbose('cli', 'node@%s', process.version);

if (opts.version) {
  return console.log(global.MDO_CLI_FULL_VERSION);
}

var app = require('../lib/app');
var strings = require('ibm-strings');

var remainingArgs = opts.argv.remain;
var command = 'help'; // the default command

if (remainingArgs[0]) {
  command = remainingArgs.shift();
}

if (!app.commands[command]) {
  var invalidCMD = errors.getError('INVALIDCMD', command);
  strings.fatal(invalidCMD.description);
  log.verbose('code', invalidCMD.errno);
  process.exit(invalidCMD.errno);
}

// Pass the command to subcommands, but remove flags in knownFlags and
// remove the command name
var knownFlags = ['ddebug', 'debug', 'no-color', 'noprompt'];
var argsWithoutCommand = opts.argv.cooked.reduce(function(args, word, index) {
  if (word.charAt(0) !== '-' ||
      knownFlags.indexOf(word.replace(/(^-+)/g, '')) === -1) {
    // word is not a flag or it is a flag that is not in knownFlags
    args.push(opts.argv.original[index]);
  }
  return args;
}, []);
argsWithoutCommand.splice(argsWithoutCommand.indexOf(command), 1);
log.silly('cli', 'arguments passed to subcommand', argsWithoutCommand);

//run mobilefirst command
// Use the original arguments so that any flags can be parsed out later
return app.commands[command](argsWithoutCommand).then(function(code) {
  // resolvers can pass an exit code if necessary
  log.verbose('cli', 'finish with mobilefirst %s', command);
  log.verbose('code', code || 0);
  process.exit(code || 0);
}, function(error) {
  // rejectors can pass an error if necessary
  log.verbose('cli', 'error, finish with mobilefirst %s', command);
  if (typeof error === 'string') {
    log.verbose('error_description', error);
  } else if (error && error.description) {
    log.verbose('error_description', error.description);
    log.verbose('code', error.errno || -1);
  }
  process.exit(error && error.errno ? error.errno : -1);
});
