/**
 * Created by TalhaAkkas on 18/08/15.
 */


var MAX_WAITING_TIME = 1 * 25 * 1000;

function construct(constructor, args) {
	function F() {
		return constructor.apply(this, args);
	}
	F.prototype = constructor.prototype;
	return new F();
}
var req = {};
//Emit 'giveMeTheFibo' in all the child/background threads.
self.onmessage = function (msg) {
	var data = msg.data;
	req.lastMessageTime = Date.now();
	setTimeout(function(){
        req.checkTimeOut();
    }, MAX_WAITING_TIME + 100);



	if(data.type == "INIT"){
		require(data.path).init(req);
		req.elderwand.threads.setTotalMaxWorkingThreads(1);
	}else if(data.type == "TERMINATE"){
	}else{

		misson(data);
	}
};
req.checkTimeOut = function(){
    if(Date.now() - req.lastMessageTime > MAX_WAITING_TIME){
        //EWLog({type:"TIMEOUT"})
       // process.send(JSON.stringify({type:"TIMEOUT"}));
        //process.kill(15)
    };
}


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.push(callback);
	//EWLog(req.elderwand.threads.getFunctionRegistery(), data.modelName,data.functionName);
	var func = req.elderwand.threads.getRegisteredFunction(data.modelName,data.functionName);

	try{
		//EWLog(">>>")
		func.apply(null, arguments);
		//EWLog("<<<")
	}catch(e){
		EWLog("-----------111111", data.modelName,data.functionName)
		EWLog(e)
	}
}
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);

		}
	}
};