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

// Public modules
var log = require('npmlog');
var Q = require('q');
// Private modules
var consts = require('./consts.js');
var exec = require('mdo-exec');
var errors = require('mdo-errors');

// Set log level
if (global.MDO_CLI_LOG_LEVEL)
    log.level = global.MDO_CLI_LOG_LEVEL;

/*
 Silly logs a message.

 message - Message to log
 */
function logSilly(message) {
    log.silly(consts.MODULE, message);
}

/*
 Verbose logs a message.

 message - Message to log
 */
function logVerbose(message) {
    log.verbose(consts.MODULE, message);
}

/*
 Invokes "cordova prepare" with the optionally passed arguments. A promise is
 returned that is either resolved, or rejected based on the result of the
 command.
 */
module.exports = function (args) {
    var cordovaArgs;    // Cordova arguments
    var debugArgs;      // Cordova debug arguments
    var d = Q.defer();

    logVerbose('Invoking prepare.');

    // Determine log level to pass to exec()
    if (log.level === consts.SILLY_LEVEL)
        debugArgs = consts.SILLY_ARG;
    else if (log.level === consts.VERBOSE_LEVEL)
        debugArgs = consts.VERBOSE_ARG;

    cordovaArgs = [consts.PREPARE_ARG];

    // Initialize args if necessary
    if (!args)
        args = [];

    cordovaArgs = cordovaArgs.concat(args);

    // Add debug args to exec args
    if (debugArgs)
        cordovaArgs.push(debugArgs);

    logSilly('Debug arguments: ' + debugArgs);
    logSilly('Cordova arguments: ' + cordovaArgs);

    //Check that cordova is installed globally
    exec.run(consts.CORDOVA_CMD, ['-v'])
    .then(function () {
      exec.run(consts.CORDOVA_CMD, cordovaArgs)
      .then(function () {
        d.resolve();
      }, function (err) {
        d.reject(err);
      });
    },function () {
      var cordovaNotGlobalErr = errors.getError('CORDOVANOTINSTALLED');
      d.reject(cordovaNotGlobalErr);
    });

    return d.promise;
};
