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

// Public modules
var fs = require('fs');
var log = require('npmlog');
var path = require('path');
var Q = require('q');

// Private modules
var consts = require('./consts.js');
var exec = require('mdo-exec');
var errors = require('mdo-errors');

var moduleName = 'generateChecksum';

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

/*
 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 (configXMLDir, args) {
    var checksumArgs;    // checksum script arguments
    var debugArgs;      // Cordova debug arguments
    var d = Q.defer();

    log.verbose(moduleName, 'Invoking checksum script.');

    // 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;
    //Check that plugin is present and the checksum script is present
    var cordovaMFPPluginPath = path.resolve(configXMLDir, 'plugins', 'cordova-plugin-mfp');
    log.silly(moduleName, 'cordova mfp plugin path: ' + cordovaMFPPluginPath);

    var checksumScriptPath = path.resolve(cordovaMFPPluginPath, 'lib', 'mfp-checksum-cli.js');
    log.silly(moduleName, 'checksum script path: ' + checksumScriptPath);

    if(!verifyFileOrFolderExists(cordovaMFPPluginPath, false)) {
      d.reject(errors.getError('CORDOVAMFPPLUGINNOTINSTALLED'));
    } else if(!verifyFileOrFolderExists(checksumScriptPath, true)) {
      d.reject(errors.getError('SCRIPTNOTPRESENT', 'mfp-checksum-cli.js'));
    } else {
      checksumArgs = [checksumScriptPath];
      checksumArgs = checksumArgs.concat(args);

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

      log.silly(moduleName, 'Debug arguments: ' + debugArgs);
      log.silly(moduleName, 'Checksum arguments: ' + checksumArgs);

      d.promise = exec.run('node', checksumArgs);
    }

    return d.promise;
};

function verifyFileOrFolderExists(path, isFile) {
  try {
    var fileStat = fs.statSync(path);
    if(isFile) {
      return fileStat.isFile();
    } else {
      return fileStat.isDirectory();
    }
  } catch (err) {
    return null;
  }
}
