/*
	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.
*/


'use strict';

var fs = require('fs');
var log = require('npmlog');
var nopt = require('nopt');
var path = require('path');
var Q = require('q');
var errors = require('mdo-errors');
var strings = require('ibm-strings');
var externalizedStrings = require('./externalizedStrings');
var _actionExtensions;

function getActionExtensions() {
  if (!_actionExtensions) {
    var findExtensions = require('pluggington');

    _actionExtensions = findExtensions(global.MDO_MAIN_EXTENSIONS_PATH, 'mdo.cli.app.actions');
  }

  return _actionExtensions;
}

/**
 * actually do the work of the command
 */
module.exports.run = function(argv) {
  var deferred = Q.defer();
  var actions = {};
  var actionExtensions = getActionExtensions();
  var actionToRun = argv[0];
  var error;

  if(actionExtensions) {
    actionExtensions.forEach(function(action){
      var actionName = action.name;
      actions[actionName] = action.export.run;
    });
  }

  if (!actionToRun) {
    error = errors.getError('MISSINGACTION', 'app');
    strings.fatal(error.description);
    deferred.reject(error);
  } else if (!actions[actionToRun]) {
    error = errors.getError('INVALIDACTION', actionToRun, 'app');
    strings.fatal(error.description);
    deferred.reject(error);
  } else {
    actions[actionToRun](argv.slice(1)).then(function(){
      deferred.resolve();
    }, function(err) {
      deferred.reject(err);
    });
  }

  return deferred.promise;
};

/**
 * print command specific help to the console
 */
module.exports.help = function(argv) {
  var deferred = Q.defer();
  var actions = {};
  var file;
  var actionExtensions = getActionExtensions();

  if (actionExtensions) {
    actionExtensions.forEach(function(action){
      var actionName = action.name;
      actions[actionName] = action.export.help;
    });
  }

  var opts = nopt({
    debug: Boolean,
    ddebug: Boolean,
  }, {
    d: '--debug',
    dd: '--ddebug'
  }, argv, 0);

  var actionToRun = opts.argv.remain[0];
  if (!actions[actionToRun]) {
    file = path.join(__dirname, '..', 'doc', 'app.txt');
  } else {
    file = actions[actionToRun]();
  }

  printHelp(actionToRun, file).then(function () {
      deferred.resolve();
  }).fail(function (err) {
      deferred.reject(err);
  });

  return deferred.promise;
};

function printHelp(actionToRun, file) {
    var deferred = Q.defer();

    log.verbose('help', 'reading file:%s', file);
    fs.readFile(file, {
        encoding: 'utf8'
      }, function (err, data) {
        if (err) {
          var invalidCMD = errors.getError('INVALIDHELPCMD', actionToRun);
          strings.fatal(strings.format(externalizedStrings.invalidAppHelp, actionToRun));
          deferred.reject(invalidCMD);
        } else {
          console.log(data);
          deferred.resolve();
        }
      }
    );
  return deferred.promise;
}
