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

var Q = require('q');
var inquirer = require('inquirer');
var path = require('path');
var nopt = require('nopt');

var strings = require('ibm-strings');
var errors = require('mdo-errors');
var externalizedStrings = require('./externalizedStrings');
var profileIO = require('mdo-server-support').profileIO;
var serverRegEx = require('./server-add').serverRegEx;

module.exports.validate = function(args) {
  var deferred = Q.defer();

  var opts = nopt({
    debug: Boolean,
    ddebug: Boolean,
  }, {
    d: '--debug',
    dd: '--ddebug'
  }, args, 0);

  if (opts.argv.remain.length > 0) {
    if (opts.argv.remain.length === 1) {
      // Check server name
      var serverName = args[0];
      if (!serverName.match(serverRegEx)) {
        var invalidServerName = errors.getError('INVALIDSERVERNAME');
        deferred.reject(invalidServerName);
      }
      else {
        deferred.resolve(opts);
      }
    }
    else { // invalid arguments found
      var badArguments = errors.getError('BADSERVERARGS', 'remove');
      deferred.reject(badArguments);
    }
  }
  else {
    deferred.resolve(opts);
  }
  return deferred.promise;
};

module.exports.run = function(args, profiles) {
  var deferred = Q.defer();

  if (args.argv.remain.length === 0) { // Interactive mode
    var choices = [];
    for (var i in profiles.servers) {
      if (i !== profiles.defaultServer) {
        choices.push(i);
      }
    }
    if (choices.length === 0) {
      var MISSINGSERVERPROFILES = errors.getError('MISSINGSERVERPROFILES', 'remove');
      deferred.reject(MISSINGSERVERPROFILES);
    }
    else {
      inquirer.prompt([
          {
            name: 'serverName',
            message: externalizedStrings.selectServerProfileToRemove,
            type: 'list',
            choices: choices
          },
          {
            name: 'confirmation',
            message: externalizedStrings.confirmRemoveServerProfile,
            type: 'confirm',
            default: true
          }], function (answers) {
          // if confirmation equals true, remove server
          if (answers.confirmation) {
            removeServer(profiles, answers.serverName)
              .then(function () {
                deferred.resolve();
              }).fail(function (error) {
                deferred.reject(error);
            });
          }
          else
            deferred.resolve();
        }
      );
    }
  }
  else { // Direct mode
    // Remove server
    var serverName = args.argv.remain.shift();
    removeServer(profiles, serverName)
      .then(function () {
        deferred.resolve();
      }).fail(function (error) {
      deferred.reject(error);
    });
  }
  return deferred.promise;
};

// return the help object for the main mdo help command to show
module.exports.getMainHelp = function() {
  var help = {
    "SERVERS" : [
      {"server remove" : externalizedStrings.serverRemoveDescription}
    ]
  };
  return help;
};

// return the path to the help file (relative to basePath) for the specific command
module.exports.getHelpFilePath = function(basePath) {
  return path.join(basePath, 'mdo-cmd-server', 'doc', 'remove.txt');
};

function removeServer(profiles, serverName) {
  var deferred = Q.defer();

  //Verify server to be removed exists in server_profiles.json
  if (profiles.servers[serverName] === undefined) {
    var serverDoesNotExists = errors.getError('SVRDOESNOTEXISTS', serverName);
    deferred.reject(serverDoesNotExists);
  }
  else if (serverName === profiles.defaultServer) {
    var serverCanNotBeDeleted = errors.getError('ERRDEFAULTSERVERCANNOTBEDELETED', serverName);
    deferred.reject(serverCanNotBeDeleted);
  }
  else {
    // Delete key from server_profiles.json
    delete profiles.servers[serverName];
    profileIO.writeServerProfiles(profiles).then(function () {
      strings.success(strings.format(externalizedStrings.successServerProfileRemoved, serverName));
      deferred.resolve();
    }).fail(function (error) {
      deferred.reject(error);
    });
  }
  return deferred.promise;
}
