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


/*
 This is the code that's .load()ed into the child/background threads:

 function fibo (n) {
 return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1;
 }

 thread.on('giveMeTheFibo', function onGiveMeTheFibo (data) {
 this.emit('theFiboIs', fibo(+data)); //Emits 'theFiboIs' in the parent/main thread.
 });

 */
//require('./config/environment')();
//var mongoose = require('mongoose');
//var config = require('config');
//global.rekuire = require('rekuire');
//var MongoClient = require('mongodb').MongoClient;
//var  assert = require('assert');
//
//var fs = require('fs');
//global.getRawDB = function(cb){
//    if(global.rawDB){
//        cb(global.rawDB);
//    }else{
//        MongoClient.connect(config.db, function(err, db) {
//            assert.equal(null, err);
//            console.log("Connected correctly to server");
//            global.rawDB = db;
//            cb(global.rawDB);
//        });
//    }
//};
//
//// Connect to mongodb
//var connect = function () {
//    var options = { server: { poolSize: 1, socketOptions: { keepAlive: 1 } } };
//    mongoose.connect(config.db, options)
//};
//mongoose.connection.on('error', console.log);
//mongoose.connection.on('disconnected', connect);
//connect();
//fs.readdirSync(__dirname + '/app/models').forEach(function (file) {
//    if (~file.indexOf('.js')) require(__dirname + '/app/models/' + file);
//});



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;
    if(data.type == "INIT"){
        require(data.path).init(req);
        req.elderwand.threads.setTotalMaxWorkingThreads(1);
    }else if(data.type == "TERMINATE"){
    }else{
        var model = req.mongoose.model(data.modelName);
        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);
        model[data.functionName].apply(model, 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);

        }
    }
};