/*
	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 _actionExtensions;

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

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

    _actionExtensions = findExtensions(global.MDO_MAIN_EXTENSIONS_PATH, 'mdo.cli.adapter.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] = action.export.run;
    });
  }

  var actionToRun = argv[0];

  if(!actionToRun) {
    var missingAction = errors.getError('MISSINGACTION', externalizedStrings.adapter);
    strings.fatal(missingAction.description);
    log.verbose('code', missingAction.errno);
    deferred.reject(missingAction);
  } else if(!actions[actionToRun]) {
    var invalidAction = errors.getError('INVALIDACTION', actionToRun, externalizedStrings.adapter);
    strings.fatal(invalidAction.description);
    log.verbose('code', invalidAction.errno);
    deferred.reject(invalidAction);
  } else if (actionToRun === 'call') {
    // adapter call doesn't need mvn
    actions[actionToRun](argv.slice(1)).then(function () {
      deferred.resolve();
    }, function (err) {
      deferred.reject(err);
    });
  }
  else {
    // check for mvn first
    exec('mvn', ['-v']).then(function () {
      actions[actionToRun](argv.slice(1)).then(function () {
        deferred.resolve();
      }, function (err) {
        deferred.reject(err);
      });
    }, function () {
      var missingMVN = errors.getError('MISSINGMVN');
      strings.fatal(missingMVN.description);
      log.verbose('code', missingMVN.errno);
      deferred.reject(missingMVN);
    });
  }

  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.getHelpFilePath;
    });
  }

  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', 'adapter.txt');
  } else {
    file = actions[actionToRun](path.join(__dirname, '..', '..'));
  }

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

  return deferred.promise;
};

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

  if (fs.existsSync(file)) {
    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(invalidCMD.description);
          deferred.reject(invalidCMD);
        } else {
          console.log(data);
          deferred.resolve();
        }
      }
    );
  } else {
    var invalidCMD = errors.getError('INVALIDHELPCMD', actionToRun);
    strings.fatal(invalidCMD.description);
    deferred.reject(invalidCMD);
  }
  return deferred.promise;
}
