/*
    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 fs = require('fs');
var path = require('path');
var nopt = require('nopt');
var et = require('elementtree');

var externalizedStrings = require('./externalizedStrings');
var errors = require('mdo-errors');
var strings = require('ibm-strings');
var exec = require('mdo-exec').run;
var urlFormatter = require('url');
var serverSupport = require('mdo-server-support');


var pushAdapter = function(serverURL, username, password, runtime, configFileName) {
  var deferred = Q.defer();

  var mavenParams = [
    'adapter:configpush',
    '-DmfpfUrl=' + serverURL,
    '-DmfpfUser=' + username,
    '-DmfpfPassword=' + password,
    '-DmfpfRuntime=' + runtime,
    '-DmfpfConfigFile=' + configFileName
  ];

  console.log(strings.format(externalizedStrings.pushingAdapter, runtime, serverURL));

  exec('mvn', mavenParams).then(function() {
    deferred.resolve();
  }, function(err) {
    deferred.reject(err);
  });

  return deferred.promise;
};


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

  // Check for pom.xml
  if (!fs.existsSync('pom.xml') || !fs.existsSync(path.join('src', 'main', 'adapter-resources', 'adapter.xml'))) {
    var nonAdapterError = errors.getError('NONADAPTERFOLDER');
    strings.fatal(nonAdapterError.description);
    deferred.reject(nonAdapterError);
  }
  else {
    var opts = nopt({
      xml: Boolean,
      password: String,
      configFile: path
    }, {
      x: '--xml',
      p: '--password',
      c: '--configFile'
    }, argv, 0);

    var mfpConfigFile = opts.configFile ? opts.configFile : 'config.json'; //get config file name, if not specified default is config.json

    if (opts.xml) {
      var data = fs.readFileSync('pom.xml').toString();
      var etree = et.parse(data);

      var defaultURL = etree.findtext('.//mfpfUrl');
      var defaultUsername = etree.findtext('.//mfpfUser');
      var defaultPassword = etree.findtext('.//mfpfPassword');
      var defaultRuntime = etree.findtext('.//mfpfRuntime');
      // override with default values in pom.xml
      console.log(strings.format(externalizedStrings.defaultServerURL, defaultURL));
      console.log(strings.format(externalizedStrings.defaultUsername, defaultUsername));
      console.log(externalizedStrings.defaultPassword);
      console.log(strings.format(externalizedStrings.defaultRuntime, defaultRuntime));
      pushAdapter(defaultURL, defaultUsername, defaultPassword, defaultRuntime, mfpConfigFile).then(function () {
        console.log(externalizedStrings.successfulPush);
        deferred.resolve();
      }, function (err) {
        console.log(externalizedStrings.errorPush);
        console.log(err.stdOut);
        var errorPush = errors.getError('ADAPTERPUSHERROR');
        strings.fatal(errorPush.description);
        deferred.reject(errorPush);
      });
    }
    // 0: default server profile, 1: specified server profile, 2: specified server profile and runtime
    else if (opts.argv.remain.length <= 2) {
      serverSupport.getServerDetails(opts.argv.remain[0], opts.argv.remain[1], opts.password, true).then(function(serverProfile) {
        var serverURL = urlFormatter.resolve(urlFormatter.format({protocol:(serverProfile.protocol || 'http'), hostname: serverProfile.host, port: serverProfile.port}), serverProfile.contextRoot);
        var username = serverProfile.userName;
        var password = serverProfile.userPassword;
        var runtime = serverProfile.runtime;
        pushAdapter(serverURL, username, password, runtime, mfpConfigFile).then(function () {
          console.log(externalizedStrings.successfulPush);
          deferred.resolve();
        }, function (err) {
          console.log(externalizedStrings.errorPush);
          console.log(err.stdOut);
          var errorPush = errors.getError('ADAPTERPUSHERROR');
          strings.fatal(errorPush.description);
          deferred.reject(errorPush);
        });
      }, function(err) {
        strings.fatal(err.description);
        deferred.reject(err);
      });

    }
    else {
      // invalid params
      var invalidParams = errors.getError('INVALIDADAPTERPARAMS');
      strings.fatal(invalidParams.description);
      deferred.reject(invalidParams);
    }
  }

  return deferred.promise;
};

// return the path to the md file (relative to basePath) for the specific command
module.exports.getHelpFilePath = function(basePath) {
  return path.join(basePath, 'mdo-adapter-actions', 'doc', 'push.txt');
};
