/**************************************************************
 ***** Creates APPX Connector service process for Windows, *****
 ************** Linux, and Mac operating systems ***************
 **************************************************************/

var serverConnectorInstallVersionStr = "5.4.4";
var serverConnectorInstallVersionNum = 50404.010;

var exec = require('child_process').execSync, child;

// Make sure the requird modules are installed.
var modules = [
    'crypto',
    'fs',
    'hexy',
    'http',
    'https',
    'mime',
    'mongodb',
    'net',
    'node-cryptojs-aes',
    'string',
    'string_decoder',
    'url',
    'ws'
];

console.log("");
console.log("Checking for required modules...");
checkMongo()

var allReqInstalled = true;
function moduleTest(){
    modules.forEach(function(name){
	if( ! testForModule(name) )
	    allReqInstalled = false;
    });

    console.log("");

    if( ! allReqInstalled ) {
	console.log("Missing modules.  Please install required modules and run again.");
	process.exit();
    }
}

//Detects OS and sets the Service variable accordingly.
switch(process.platform){
     case 'win32':
	 var Service = require('node-windows').Service; break;
     case 'linux':
	 var Service = require('node-linux').Service; break;
     case 'darwin':
	 var Service = require('node-mac').Service; break;
}


//Create new service object
var svc = new Service({
    name: 'appxConnector',
    description: 'Connector that allows appx client to talk to server.',
    script: 'appxConnector.js',
    
    //Set variable so appxConnector.js knows where to push files to.
    env:[{
	name: "APPX_CONNECTOR_DIR",
	value: require('path').resolve(__dirname)
    },{
	name: "NODE_ENV",
	value: "production"
    }]
});

//Installs service
svc.on('alreadyinstalled', function(){
    console.log("Already installed, restarting appxconnector service...");
    svc.stop();
    svc.start();
    console.log("Done");
});

svc.on('install', function(){
    console.log("Installing appxconnector service...");
    setTimeout(function(){
	svc.start();
    },5000);
    
    console.log("Done");
});

svc.on('start', function(){
    console.log("Service started");
});

function testForModule(name) {
    var nameStr = name + "                              ";
    process.stdout.write("Module: " + nameStr.substring(0,25) + " - ");
    if( isModuleInstalled(name) ) {
	console.log("Installed.");
	return true;
    }
    else {
	console.log("Missing, please run 'npm install " + name + "' to install.");
	return false;
    }
}

function isModuleInstalled(name) {
    try {
	require.resolve(name);
	return true;
    }
    catch(ex) {
	return false;
    }
}

function checkMongo(){
    var mongoDatabase    = "AppxDatabaseCache";
    var mongoHost        = "localhost";
    var mongoPort        = 27017;
    var MongoClient = require('mongodb').MongoClient;
    var MongoServer = require('mongodb').Server;
    try{
	var mongoClient = new MongoClient(new MongoServer(mongoHost, mongoPort));
	var mongoUrl    = 'mongodb://'+mongoHost+':'+mongoPort+'/'+mongoDatabase;
	var mongoCacheDb = null;

	mongoClient.connect(mongoUrl,function (err, db) {

	    mongoCacheDb = db;
	    if(err){
		console.log("Unable to connect to MongoDatabase Server. Make sure MongoDB server has been installed, configured, and started on your server before continuing. This is a separate setup from installing the driver using 'npm install mongodb'. You need to visit the website and follow the instructions for installing the server. (https://www.mongodb.org/downloads)");
		process.exit();
	    }
	    moduleTest();
	    console.log("Installing appxconnector service...");
	    svc.install();
	});

    }catch(ex){
	console.log(ex);
    }
}
