/*
	Licensed Material - Property of IBM

	(C) Copyright 2015 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');

function printFileContents(filepath) {
  var deferred = Q.defer();

  var fs = require('fs');

  fs.readFile(filepath, {
    encoding: 'utf8'
  }, function(err, data) {
    if (err) {
      deferred.reject(err);
    } else {
      console.log(data);
      deferred.resolve();
    }
  });

  return deferred.promise;
}

function printHelpHeader() {
  return printFileContents(path.resolve(__dirname, '..', 'resources', 'help_header.txt'));
}

function printHelpFooter() {
  return printFileContents(path.resolve(__dirname, '..', 'resources', 'help_footer.txt'));
}

module.exports = function(argv) {
  var strings = require('ibm-strings');
  var errors = require('mdo-errors');
  var nopt = require('nopt');

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

  var deferred = Q.defer();

  var app = require('./app');

  var command = opts.argv.remain[0];

  if (command !== undefined) {
    if (app.externalHelp[command]) {
      // slice out the index of the command
      app.externalHelp[command](argv.slice(argv.indexOf(command) + 1))
      .then(deferred.resolve, deferred.reject);
    } else {
      var invalidCMD = errors.getError('INVALIDCMD', argv[0]);
      strings.fatal(invalidCMD.description);
      deferred.reject(invalidCMD);
    }
  } else {
    printHelpHeader().then(function() {
      printExtendedHelp();

      return printHelpFooter();
    }).then(function() {
      deferred.resolve();
    });
  }

  return deferred.promise;
};

function printExtendedHelp() {
  var sprintf = require('sprintf-js').sprintf;

  var findExtensions = require('pluggington');

  var extendedHelpContribs = findExtensions(global.MDO_MAIN_EXTENSIONS_PATH, 'mdo.cli.help');
  var allContributedHelp = [];

  if (extendedHelpContribs) {
    extendedHelpContribs.forEach(function(contrib) {
      var contribJSON = contrib.export.getHelp();
      for (var key in contribJSON) {
        var exists = false;
        for (var i = 0; i < allContributedHelp.length; i++) {
          var group = allContributedHelp[i];
          if (key in group) {
            group[key] = group[key].concat(contribJSON[key]);
            exists = true;
          }
        }
        if (!exists) {
          var newGroup = {};
          newGroup[key] = contribJSON[key];
          allContributedHelp = allContributedHelp.concat(newGroup);
        }
      }
    });

    allContributedHelp.sort(function(a, b) {
      return Object.keys(a)[0] < Object.keys(b)[0] ? -1 : 1;
    });
    allContributedHelp.forEach(function(group) {
      var groupName = Object.keys(group)[0];
      console.log("\n" + groupName);
      group[groupName].sort(function(a, b) {
        return Object.keys(a)[0] < Object.keys(b)[0] ? -1 : 1;
      });
      group[groupName].forEach(function(help) {
        var name = Object.keys(help)[0];
        var description = help[name];
        var leftColumnWidth = 30;
        console.log(sprintf("     %'.-" + leftColumnWidth + "s %s", name + ' ', description));
      });
    });
  }
}
