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

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

var strings = require('ibm-strings');
var errors = require('mdo-errors');
var globalConfig = require('mdo-cmd-config').config_api;
var externalizedStrings = require('./externalizedStrings');
var serverRegEx = require('./server-add').serverRegEx;
var urlFormatter = require('url');


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

  var opts = nopt({
    password: String
  }, {
    p: '--password'
  }, args, 0);

  if (opts.argv.remain.length > 0) {
    if (opts.argv.remain.length === 1) {
      var serverName = opts.argv.remain[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', 'console');
      deferred.reject(badArguments);
    }
  }
  else {
    deferred.resolve(opts);
  }
  return deferred.promise;
};

// return the help object for the main mdo help command to show
module.exports.getMainHelp = function() {
  var help = {
    "SERVERS" : [
      {"server console" : externalizedStrings.serverConsoleDescription}
    ]
  };
  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', 'console.txt');
};


/*
 * Opens the MobileFirst console for the current project
 */
module.exports.run = function (args, profiles) {
  var deferred = Q.defer();

  var serverName = args.argv.remain.shift();
  if (serverName === undefined) {
    serverName = profiles.defaultServer;
  }

  if (profiles.defaultServer === undefined) {
    var noprofiles = errors.getError('MISSINGSERVERDEFINITION');
    deferred.reject(noprofiles);
  }
  else if (!profiles.servers.hasOwnProperty(serverName)) {
    var profilenotfound = errors.getError('SVRDOESNOTEXISTS', serverName);
    deferred.reject(profilenotfound);
  }
  else {
    var server = profiles.servers[serverName];
    var noPrompt = global.MDO_CLI_NO_PROMPT;
    inquirer.prompt([
      {
        name: 'password',
        message: externalizedStrings.whatServerPassword,
        type: 'password',
        when: function () {
          return (noPrompt !== true && args.password === undefined &&
            (!server.hasOwnProperty('password') || server.password === ''));
        }
      }],
      function (answers) {
        var password;
        if (answers.password !== undefined) {
          password = answers.password;
        }
        else {
          password = args.password || new Buffer(server.password, 'base64');
        }

        var options = {
          protocol: server.protocol,
          host: server.host,
          port: server.port,
          path: server.path,
          userName: server.login,
          userPassword: password,
          contextRoot: server.contextRoot,
          timeout: server.timeout
        };

        openOnBrowser(serverName, options).then(function(){
          // On Windows, the timing of the open() call is such that resolving
          // this deferred seems to exit the CLI before the browser gets opened.
          // On top of that, the child process returned from open() doesn't
          // have a good way to check "yes I opened successfully". Therefore,
          // we don't know exactly when this can be resolved. Weak dude.
          //deferred.resolve();
        }).catch(function(err){
          deferred.reject(err);
        });
      });
  }
  return deferred.promise;
};


function openOnBrowser(serverName, options) {
  strings.info(strings.format(externalizedStrings.openConsole, serverName));
  
  //adds support for IPv6 addresses
  //by wrapping the addess in [] inside the url
  var url;
  if(typeof server.path !== 'undefined' && server.path.length > 1){
    url =  urlFormatter.format({protocol:(options.protocol || 'http') , hostname: options.host, port: options.port}) + `${server.path}/mfpconsole/index.html#/dashboard` +
    '&login=' + options.userName + '&password=' + options.userPassword;
  }
  else{
    url =  urlFormatter.format({protocol:(options.protocol || 'http') , hostname: options.host, port: options.port}) + '/mfpconsole/index.html#/dashboard' +
    '&login=' + options.userName + '&password=' + options.userPassword;
  }
  //get the development browser value from global config
  return globalConfig.getDevelopmentBrowser()
    .then(function (browser) {
      if (browser === globalConfig.values.DEFAULT_BROWSER) {
        open(url);
      }
      else {
        open(url, browser);
      }
    });
}
