/**
 * Created by TalhaAkkas on 16/04/15.
 */

var iconv = require('iconv-lite');
iconv.extendNodeEncodings();
var jsdom = require("jsdom");
var redis = require('redis');
var redisClient = undefined

//var jquery = require('jquery')(require("jsdom").jsdom().parentWindow);

//require('./config/environment')();
var rekuire = require('../../node_modules/rekuire');
require('../../Environment')();
var utils = require("../../Utils");
var parsers = {};
var ChildWorker = {};
var parseFunctions = ['Data', 'Links', 'Images', 'InformationPoints'];
ChildWorker.getParser = function(key){
	if(parsers[key] == undefined){
		parsers[key] = rekuire(key);
	}
	return parsers[key];
}
ChildWorker.runElement =  function (element){
	if(element.method && element.method.toUpperCase() == "POST"){
		var parser = ChildWorker.getParser(element.parserKey);
		var options = utils.createHttpPostOptions(parser.seedUrl, element.url, element.data);
		options.element = element;
		options.encoding = parser.encoding;

		utils.doRequestPost(options, ChildWorker.didReturnResponse);
	}else {
		var parser = ChildWorker.getParser(element.parserKey);
		var options = utils.createHttpOptions(parser.seedUrl, element.url);
		options.element = element;
		options.encoding = parser.encoding;

		utils.doHttpRequest(options, ChildWorker.didReturnResponse);
	}
}
ChildWorker.didReturnResponse = function (string, options, status){
	if(status == 'timeout') return ChildWorker.didEndProcess({}, options, status);
	if(status == 'error') return ChildWorker.didEndProcess({}, options, status);

	var parser = ChildWorker.getParser(options.element.parserKey);
	jsdom.env(string.replace('\n', ''), ["http://code.jquery.com/jquery.js"] ,function (errors, window) {
		var data = {};
		try{
			for(var i in parseFunctions){
				var key = "parse" + parseFunctions[i];
				if (parser[key]) {
					var info = parser[key](window.$, options);
					data[parseFunctions[i]] = info;
				}
			}
			//console.log("didEndProcess");
			ChildWorker.didEndProcess(data, options, status);
		}catch(e){
			console.log(e);
			console.log(e.stackTrace);
			ChildWorker.didEndProcess(data, options, status);
		}
	});
}
ChildWorker.didEndProcess = function(data, options, status){
	delete options.agent;
	self.sendData([data, options, status]);
}
self.onmessage = function (msg) {
	var data = msg.data;

	if(data.type == "INIT"){
	}else if(data.type == "TERMINATE"){
	}else {
		ChildWorker.runElement(data);
	}
}
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);

		}
	}
};