/*
	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 log = require('npmlog');
var global_config = require("./global.js");
var errors = require('mdo-errors');
var strings = require('ibm-strings');
var fs = require('fs');
var path = require('path');

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


  log.level = global.MDO_CLI_LOG_LEVEL ? global.MDO_CLI_LOG_LEVEL : log.level;

  switch (argv.length) {
    //no arguments show global keys in interactive mode
    case 0:
      global_config.interactiveMode().fail(function(err) {
        deferred.reject(err);
      });
      break;
      //1 argument, show interactive mode for key
    case 1:
      global_config.withKey(argv[0]).fail(function(err) {
        deferred.reject(err);
      });
      break;
      //2 arguments, update key with value
    case 2:
      global_config.withKeyAndValue(argv[0], argv[1]).fail(function(err) {
        deferred.reject(err);
      });
      break;
    default:
      strings.fatal(errors.getError('INVALIDARGS', 'config').description);
      break;
  }
  return deferred.promise;
};

/**
 * print command specific help to the console
 */
module.exports.help = function() {
  var d = Q.defer();
  
  fs.readFile(path.resolve(__dirname, '..', 'help', 'help.txt'), {
    encoding: 'utf8'
  }, function(err, data) {
    if (err) {
      d.reject(err);
    } else {
      console.log(data);
      d.resolve();
    }
  });

  return d.promise;
};

/*
 * Export config-json-api
 */
module.exports.config_api = require("./config_api.js");
