/*
	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 fs = require('fs');
var log = require('npmlog');
var nopt = require('nopt');
var path = require('path');
var Q = require('q');
var errors = require('mdo-errors');
var strings = require('ibm-strings');
var externalizedStrings = require('./externalizedStrings');
var consts = require('./constants');
var serverSupport = require('mdo-server-support');
var serverDefaults = serverSupport.getServerDefaults;
var profileIO = serverSupport.profileIO;
var dockerUtils = require('./dockerUtils');

log.level = global.MDO_CLI_LOG_LEVEL ? global.MDO_CLI_LOG_LEVEL : log.level;

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

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

  if (opts.argv.remain.length === 1) {
    var ops = opts.argv.remain[0];
    if (ops == 'start') {
      startServices().then(function() {           
        deferred.resolve();
      }).catch(function (error) {
        strings.fatal(strings.format(externalizedStrings.cmdFailed, error));
        deferred.reject(error);
      });
    } else if (ops == 'stop') {
      stopServices().then(function() {           
        deferred.resolve();
      }).catch(function (error) {
        strings.fatal(strings.format(externalizedStrings.cmdFailed, error));
        deferred.reject(error);
      });
    } else {
      var badArgs = errors.getError('BADSVCOPSARGS');
      strings.fatal(badArgs.description);
      deferred.reject(badArgs);
    }

  } else {
    var badArgs = errors.getError('BADSVCOPSARGS');
    strings.fatal(badArgs.description);
    deferred.reject(badArgs);    
  } 

  return deferred.promise;
};

/**
 * print command specific help to the console
 */
module.exports.help = function() {
  var deferred = Q.defer();

  var file = path.join(__dirname, '..', 'doc', 'mfservices.txt');
  log.verbose('help', 'reading file:%s', file);
  fs.readFile(file, {
      encoding: 'utf8'
    }, function (err, data) {
      if (err) {
        deferred.reject(err);
      } else {
        console.log(data);
        deferred.resolve();
      }
    }
  );

  return deferred.promise;
};

function startServices() {
  var deferred = Q.defer();

  getOrCreateICPAServerProfile().then(function(profile) {        
    return registerAppWithCEServer(profile);
  }).then(function () {        
    deferred.resolve(); 
  }).catch(function (error) {   
    deferred.reject(error);
  });

  return deferred.promise;
}

function stopServices() {
  var deferred = Q.defer();

  dockerUtils.stopContainer(consts.CE_IMAGE).then(function() {    
    strings.info(strings.format(externalizedStrings.serverStopped));         
    deferred.resolve(); 
  }).catch(function (error) {   
    deferred.reject(error);
  });

  return deferred.promise;
}

function getRegisterCommand() {
  var registerCommand = null;
  var findExtensions = require('pluggington');
  var commands = findExtensions(global.MDO_MAIN_EXTENSIONS_PATH, 'mdo.cli.app.actions');
  commands.forEach(function(command){
    if (command.name == 'register') { 
      registerCommand = command;         
    }
  });
  return registerCommand;
}

function getOrCreateICPAServerProfile() {
  var deferred = Q.defer();

  profileIO.getServerProfiles(false, false).then(function (profiles) {
    if (profiles.servers[consts.ICPA_SERVER] === undefined) {
      log.verbose(consts.LOG_PREFIX, 'Server profile ' + consts.ICPA_SERVER + ' not found.');
      profiles.servers[consts.ICPA_SERVER] = {
        'protocol': serverDefaults.PROTOCOL,
        'host': serverDefaults.HOST,
        'port': serverDefaults.PORT,
        'path': serverDefaults.PATH,
        'login': serverDefaults.CREDENTIALS,
        'password': Buffer.alloc(serverDefaults.CREDENTIALS.length, serverDefaults.CREDENTIALS).toString('base64'),
        'contextRoot': serverDefaults.CONTEXT_ROOT,
        'timeout': serverDefaults.TIMEOUT_SECONDS
      };          
    } else {
      log.verbose(consts.LOG_PREFIX, 'Server profile ' + consts.ICPA_SERVER + ' already exists.');
    }
    profileIO.handleLocalHost(false, profiles, consts.ICPA_SERVER, false).then(function () {
      log.verbose(consts.LOG_PREFIX, 'Server profile ' + consts.ICPA_SERVER + ' added or updated successfully.');
      deferred.resolve(profiles.servers[consts.ICPA_SERVER]);
    }).fail(function (error) {
      deferred.reject(error);
    });      
  }).catch(function (error) {
    deferred.reject(error);
  });

  return deferred.promise;
}

function registerAppWithCEServer(profile) {
  var deferred = Q.defer();

  strings.info(externalizedStrings.pullDocker);
  dockerUtils.pullImage(consts.CE_IMAGE).then(function() {
    strings.info(externalizedStrings.startServer);
    dockerUtils.startContainer(consts.CE_IMAGE, profile).then(function(server) {
      strings.info(strings.format(externalizedStrings.serverRunning, server.url));
      getRegisterCommand().export.run([ consts.ICPA_SERVER ]).then(function() {           
        deferred.resolve();
      }).catch(function (error) {
        log.verbose(consts.LOG_PREFIX, 'Failed to register application. Reason:' + error);
        deferred.reject(error);
      }); 
    }).catch(function(err) {
      log.verbose(consts.LOG_PREFIX, 'Failed to start container. Reason:' + err);
      deferred.reject(err);
    });
  }).catch(function(err) {
    log.verbose(consts.LOG_PREFIX, 'Failed to pull docker image. Reason:' + err);
    deferred.reject(err);
  });

  return deferred.promise;
}
