/*
	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 Q = require('q');
var path = require('path');
var nopt = require('nopt');

var errors = require('mdo-errors');
var strings = require('ibm-strings');
var serverHelp = require('./help');
var profileIO = require('mdo-server-support').profileIO;

var _actionExtensions;

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

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

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

  if (actionExtensions) {
    actionExtensions.forEach(function(action){
      var actionName = action.name;
      actions[actionName] =
        {
          "validate": action.export.validate,
          "run": action.export.run,
          "createLocalProfile": action.createLocalProfile,
          "conditionalCreate": action.conditionalCreate
        };
    });
  }

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

  var actionName = opts.argv.remain[0];
  var actionToRun = actions[actionName];
  if (!actionName) {
    var missingSvrAction = errors.getError('MISSINGSVRACTION');
    strings.fatal(missingSvrAction.description);
    deferred.reject(missingSvrAction);
  }
  else if (!actionToRun) {
    var invalidSvrAction = errors.getError('INVALIDSVRACTION', actionName);
    strings.fatal(invalidSvrAction.description);
    deferred.reject(invalidSvrAction);
  }
  else {
    // Start by removing the action and any debug flags from the arguments
    var args = argv.slice(1);
    actionToRun.validate(args).then(function(opts){
      args = opts;
      //check if local profile should be created for the action, but
      //do not create if the action specifies a profile other than local
      var serverName = args.argv.remain[0];
      var createLocal = actionToRun.createLocalProfile &&
        (serverName === undefined || serverName === 'local');
      return profileIO.getServerProfiles(createLocal, actionToRun.conditionalCreate);
    }).then(function(profiles){
      return actionToRun.run(args, profiles);
    }).then(function(){
      deferred.resolve();
    }).catch(function(err){
      strings.fatal(err.description);
      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 actionExtensions = getActionExtensions();

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

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

  var actionToRun = opts.argv.remain[0];
  if (!actions[actionToRun]) {
    serverHelp.printServerHelp()
      .then(function () {
        deferred.resolve();
      })
      .fail(function (err) {
        deferred.reject(err);
      });
  } else {
    var file = actions[actionToRun](path.join(__dirname, '..', '..'));
    serverHelp.printServerCmdHelp(actionToRun, file)
      .then(function () {
        deferred.resolve();
      })
      .fail(function (err) {
        deferred.reject(err);
      });
  }
  return deferred.promise;
};
