let keen={},
	semusiConfig = require('./../config'),
	logger = require('../../logger'),
	moment = require("moment"),
	_ = require("underscore"),
	async = require('async'),
	client = require('node-rest-client').Client;

let KeenIo = require('keen.io');
let keenConfig = {
				    projectId: semusiConfig.keen.ProjectId,
				    writeKey: semusiConfig.keen.WriteKey,
				    readKey: semusiConfig.keen.ReadKey,
				    masterKey: semusiConfig.keen.MasterKey,
				}
let clientIo = KeenIo.configure(keenConfig);

let proxy = new client();

(function (keen) {

	keen.writeEvents =  function(appid,events,callback){
		let data = [];
		events.forEach(function(item){
			let obj = _.extend({},{"keen":{"timestamp":moment(item.eventTime*1000).toISOString()}},item);
			data.push(obj);
		});
		let formattedData = _.groupBy(data, function(obj){
		    return  "event_" + appid + "_" + obj.key ;
		});
		let args = {
		  	data: formattedData,
		  	headers:{
		  		"Authorization":semusiConfig.keen.WriteKey,
		  		"Content-Type": "application/json"
		  	}
		};

		proxy.post(semusiConfig.keen.Url + semusiConfig.keen.ProjectId + "/events", args, function(result,response) {
		  	if(result && result.error_code){
				logger.info(`keen args  => ${args.data}`);	 
			}
		  	callback(result);
		});
	};

	keen.getFunnelResults =  function (steps,callback){
		let args = {
		  	data: {steps:steps},
		  	headers:{
		  		"Authorization":semusiConfig.keen.ReadKey,
		  		"Content-Type": "application/json"
		  	}
		};
		proxy.post(semusiConfig.keen.Url + semusiConfig.keen.ProjectId + "/queries/funnel", args, function(result,response) {
			if(result.error_code){
				logger.info(`funnel keen error::${result}`);
				callback([]);
			}
			else{
				callback(result.result);
			}
		});
	};

	keen.getFunnelResultsWithActorProperty =  function (steps,callback){
		let args = {
		  	data: {steps:steps},
		  	headers:{
		  		"Authorization":semusiConfig.keen.ReadKey,
		  		"Content-Type": "application/json"
		  	}
		};

		proxy.post(semusiConfig.keen.Url + semusiConfig.keen.ProjectId + "/queries/funnel", args, function(result,response) {
			if(result.error_code){
				logger.info(`funnel keen error::: ${result}`);
				callback([]);
			}
			else{
				callback(result);
			}
		});
	};

	keen.getExtractionResults =  function (steps,callback){
		let args = {
		  	data: steps,
		  	headers:{
		  		"Authorization":semusiConfig.keen.ReadKey,
		  		"Content-Type": "application/json"
		  	}
		};

		proxy.post(semusiConfig.keen.Url + semusiConfig.keen.ProjectId + "/queries/extraction", args, function(result,response) {
			if(result.error_code){
				logger.info(`getExtractionResults keen error::: ${result}`); 
				callback([]);
			}
			else{
				callback(result.result);
			}
		});
	};

	keen.count =  function (obj){
		let query = new KeenIo.Query("count", obj);
		return query;
	};

	keen.getCounts =  function (arrayObj, callback){
		let solution = [];
		/*for(i=0;i<arrayObj.length;i++){
			clientIo.run(arrayObj[i], function(response){
				solution.push(response.result);
			});
		}*/
		async.forEach(arrayObj, function(item, callback){
			async.parallel([
                function(callback){
                	clientIo.run(item, function(response){
                    	if(response){
                    		solution.push(response.result);
                    	}
                    	else{
                    		solution.push(0);
                    	}

						callback();
					});
                   /* proxy.post(semusiConfig.keen.Url + semusiConfig.keen.ProjectId + "/queries/count", item, function(result,response) {
						if(result.error_code){
							 
							callback();
						}
						else{
							solution.push(result.result);
							callback();
						}
					});*/
                }
            ],function(err){
                if(err){
					logger.error(`error=> ${err}`);
                    callback(err);
                }
                else{
                    callback();
                }

            });
		},function(error){
			if(error) {
				logger.error(`error=> ${error}`);
				callback([]);
			}
			else{
				callback(solution);
			}
        });
	};

	keen.extractionQuery =  function (obj){
		return new KeenIo.Query("extraction", obj);
	};

	keen.prepareQuery =  function (analysis, obj){
		return new KeenIo.Query(analysis, obj);
	};

	keen.runQuery =  function (array, callback){
		clientIo.run(array, function(error, response){
			callback(error, response);
		});
	};

	keen.getEvents =  function(appid,callback){
		proxy.get(semusiConfig.keen.Url + semusiConfig.keen.ProjectId + "/events", function(result,response) {
		  	callback(result,response);
		});
	};

}(keen));

module.exports = keen;
