/*
	Licensed Material - Property of IBM

	(C) Copyright 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 strings = require('ibm-strings');
var path = require('path');
var manager = require('platform-manager');
var log = require('npmlog');
var consts = require('./consts');
var config_api = require('./config_api');
var nopt = require('nopt');
var errors = require('mdo-errors');
var cordovaSupport = require('mdo-cordova-support');

var deferred;

/*
 * Throws an error message and finish the execution with the code for the given
 * error.
 */
function throwError(error) {
  if (error && error.description)
    strings.fatal(error.description);
  deferred.reject(error);
}

function logVerbose(message) { log.verbose(consts.MODULE, message); }

function resolve(result) {
  logVerbose('Got message from config_api:');
  logVerbose(result);
  deferred.resolve(result);
}

function getPlatformInfo() {
  var d = Q.defer();
  manager.detectPlatforms().then(function(info) {
    // Found platforms
    d.resolve(info);
  }, function() {
    logVerbose('No platforms detected, check if in Cordova with no platforms');
    cordovaSupport.detect().then(function(configXMLPath) {
      d.resolve({
        isCordova: true,
        platforms: [{
          platformId: 'cordova-no-platforms',
          getAppConfigKeys: cordovaSupport.getAppConfigKeys,
          setAppConfigKey: cordovaSupport.setAppConfigKey,
          configXMLPath: configXMLPath
        }]
      });
    }, function() {
      d.reject(errors.getError('NOPLATFORMSDETECTED'));
    });
  });
  return d.promise;
}

/*
 * actually do the work of the command
 */
module.exports.run = function(argv) {
  deferred = Q.defer();
  if (global.MDO_CLI_LOG_LEVEL)
    log.level = global.MDO_CLI_LOG_LEVEL;
  logVerbose('start with mdo app config');
  getPlatformInfo().then(function(info) {
    var opts = nopt({ list: Boolean }, { l: '--list' }, argv, 0);

    logVerbose(info);

    if (opts.list) {
      // Show list
      config_api.configList(info).then(resolve, throwError);
    } else if (argv.length === 0) {
      // No arguments show global keys in interactive mode
      config_api.configWithNoArgs(info).then(resolve, throwError);
    } else if (argv.length === 1) {
      // 1 argument, show value for key
      config_api.configWithKey(info, argv[0]).then(resolve, throwError);
    } else if (argv.length === 2) {
      // 2 arguments, set key value
      config_api.configWithKeyAndVal(info, argv[0], argv[1])
      .then(resolve, throwError);
    } else {
      throwError(errors.getError('BADARGUMENTS', 'app config'));
    }
  }, function(err) {
    logVerbose('Caught error from platforms-manager');
    throwError(err);
  });

  return deferred.promise;
};

/**
 * print command specific help to the console
 */
module.exports.help = function() {
  return path.resolve(__dirname, '..', 'doc', 'config.txt');
};

