/*
	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');
var fs = require('fs');
var log = require('npmlog');

var errors = require('mdo-errors');
var strings = require('ibm-strings');
var externalizedStrings = require('./externalizedStrings');

/**
 * print info to the console for the mfp help command to show
 */
module.exports.getHelp = function() {
  return getServerExtendedHelp();
};

function getServerExtendedHelp() {
  var help = {};

  var findExtensions = require('pluggington');
  var serverActions = findExtensions(global.MDO_MAIN_EXTENSIONS_PATH, 'mdo.cli.server.actions');

  serverActions.forEach(function (action) {
    if (action.export.getMainHelp) {
      var helpObject = action.export.getMainHelp();

      for (var section in helpObject) {
        if (help[section]) {
          // section already exists, append to it
          help[section] = help[section].concat(helpObject[section]);
        } else {
          // section does not yet exist. Assign it.
          help[section] = helpObject[section];
        }
      }
    }
  });
  return help;
}

module.exports.printServerHelp = function() {
  var deferred = Q.defer();

  printHelpHeader()
    .then(function() {
      printServerExtendedHelp();
      return printHelpFooter();
    })
    .then(function() {
      deferred.resolve();
    })
    .catch(function (error) {
      deferred.reject(error);
    });

  return deferred.promise;
};

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

  //print Group Header
  console.log("\n" + externalizedStrings.serverHelpGroup);

  var contribJSON = getServerExtendedHelp();
  var groupName = Object.keys(contribJSON)[0];

  contribJSON[groupName].sort(function(a, b) {
    return Object.keys(a)[0] < Object.keys(b)[0] ? -1 : 1;
  });
  contribJSON[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));
  });
}

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, '..', 'doc', 'serverHelp_header.txt'));
}

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

module.exports.printServerCmdHelp = function (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(strings.format(externalizedStrings.invalidServerHelp, actionToRun));
          deferred.reject(invalidCMD);
        } else {
          console.log(data);
          deferred.resolve();
        }
      }
    );
  } else {
    var invalidCMD = errors.getError('INVALIDHELPCMD', actionToRun);
    strings.fatal(strings.format(externalizedStrings.invalidServerHelp, actionToRun));
    deferred.reject(invalidCMD);
  }
  return deferred.promise;
};

