/**
 * Created by TalhaAkkas on 02/09/15.
 */


var MongoClient = require('mongodb').MongoClient;
function construct(constructor, args) {
	function F() {
		return constructor.apply(this, args);
	}
	F.prototype = constructor.prototype;
	return new F();
}
var req = {};
var dbInstance = undefined;
var redis = require('redis');
var redisClient = undefined

//Emit 'giveMeTheFibo' in all the child/background threads.
//var threads = require("../threads");
self.onmessage = function (msg) {
	var data = msg.data;
	if(data.type == "INIT"){
		require(data.path).init(req);
		req.elderwand.threads.setTotalMaxWorkingThreads(1);
		MongoClient.connect(require('config').db, function(err, db) {
			dbInstance = db;
		});
		redisClient = redis.createClient();
		redisClient.on('connect', function() {
			redisClient.didConnected = true
		}
	}else if(data.type == "TERMINATE"){
		dbInstance.close();
	}else if(data.type == "REDIS"){
		if(redisClient.didConnected){
			redisClient.get(data.messageRedisId, function(err, reply) {
				if(err) console.log("REDIS ERROR", err)
				var innserMessage = JSON.parse(reply);
				self.onmessage(innserMessage)
			});
		}else{
			redisClient = redis.createClient();
			redisClient.on('connect', function() {
				redisClient.didConnected = true
				redisClient.get(data.messageRedisId, function(err, reply) {
					if(err) console.log("REDIS ERROR", err)
					var innserMessage = JSON.parse(reply);
					self.onmessage(innserMessage)
				});
			}
		}
	}else{
		if(dbInstance == undefined){
			MongoClient.connect(require('config').db, function(err, db) {
				dbInstance = db;
				misson(data);
			});
		}else{
			misson(data);
		}
	}
};
function misson(data){


	var callbackArguments = data.callbackArguments;

	var callbackBody = "var arguments = [];";
	callbackArguments.forEach(function(arg){ callbackBody += "arguments.push(" + arg + ");" });

	callbackBody += "self.sendData(arguments);";
	callbackArguments.push(callbackBody);
	var callback = construct(Function,  callbackArguments);

	var arguments = data.arguments;
	arguments.pop();
	arguments.pop();
	arguments.push(dbInstance);
	arguments.push(callback);
	var func = req.elderwand.threads.getRegisteredFunction(data.modelName,data.functionName);

	func.apply(null, arguments);
}
var BUFFER_SIZE = 512 * 1024;
self.sendData = function(data){
	var string = JSON.stringify(data);
	if(string.length < BUFFER_SIZE){
		process.send(JSON.stringify({type:"COMPLETE", data:string}));
	}else{
		var expected = Math.ceil(string.length / BUFFER_SIZE);
		for(var i = 0; i < expected; i++){
			var start = i * BUFFER_SIZE;
			var end = (i + 1) * BUFFER_SIZE < string.length ? (i + 1) * BUFFER_SIZE : string.length ;
			var total = string.length;
			var json = JSON.stringify({type:"PARTIAL", expected: expected, total: total, start: start, end:end, data:string.substring(start, end)})

			// EWLog(string.substring(start, BUFFER_SIZE).length , json.length -  BUFFER_SIZE, json.length, BUFFER_SIZE);
			process.send(json);

		}
	}
};