var moment = require('moment'),
logger = require('../../../logger'),
common = require('./../../utils/common.js'),
mongojs = require('mongojs'),
semusiConfig = require('./../../config');

var db;
if(semusiConfig.IsProduction){
    db = mongojs(semusiConfig.mongodb.productionUrl);
}
else{
    db = mongojs(semusiConfig.mongodb.localUrl);
} 

let compArr = [
	{
		"_id" :  "1d8e596a3732fca02597d4e6b342e766a19c57a6",
		"p" : "Android",
		"competingapps" : {
        "apps" : [ 
	            {
	                "state" : "I",
	                "name" : "LimeRoad",
	                "package" : "com.shopping.limeroad",
	                "id" : "5710b0703ea9dc8806a261d0",
	                "sc" : 10,
	                "tsd": 100,
	                "ls" : 1473652901
	            }
	        ]
	    }
	},
	{
		"_id" :  "2a759e97e365b3c1b735003fee1473db5e8b0be4",
		"p" : "Android",
		"competingapps" : {
        "apps" : [ 
	            {
	                "state" : "I",
	                "name" : "LimeRoad",
	                "package" : "com.shopping.limeroad",
	                "id" : "5710b0703ea9dc8806a261d0",
	                "sc" : 20,
	                "tsd": 500,
	                "ls" :1473663701
	            }, 
	            {
	                "state" : "I",
	                "name" : "Voonik",
	                "package" : "com.voonik.android",
	                "id" : "57171cccc9023bab06619218",
	                "sc" : 15,
	                "tsd": 600,
	                "ls" : 1473739301
	            }
	        ]
	    }
	},
	{
    	"_id" : "f93c2dede3bd1cab9c7943a6c9364e7d8e43ed2a",
    	"p" : "Android",
    	 "competingapps" : {
        "apps" : [ 
	            {
	                "state" : "I",
	                "name" : "craftsvilla",
	                "package" : "com.craftsvilla.app",
	                "id" : "571f3fea5782d9376b196e78",
	                "sc" : 14,
	                "tsd": 700,
	                "ls" : 1473566501
	            }
	        ]
	    }
	},
	{
    	"_id" : "f3588d629c6b9feb4782e6e7a6b866375997bb62",
    	"p" : "Android",
    	"competingapps" : {
        "apps" : [ 
	            {
	                "state" : "I",
	                "name" : "LimeRoad",
	                "package" : "com.shopping.limeroad",
	                "id" : "5710b0703ea9dc8806a261d0",
	                "sc" : 18,
	                "tsd": 680,
	                "ls" : 1473631301
	            }, 
	            {
	                "state" : "I",
	                "name" : "Voonik",
	                "package" : "com.voonik.android",
	                "id" : "57171cccc9023bab06619218",
	                "sc" : 21,
	                "tsd": 300,
	                "ls" : 1473717701
	            }
	        ]
	    }
	}
];
let resultArray = [];
let counter = 0;
compArr.forEach(function(item){
	if(item.p && item.p != '' && item.p != undefined){
		let platform = item.p.toLowerCase();
		if(item.competingapps && item.competingapps.apps.length > 0){
			item.competingapps.apps.forEach(function(value){
				updateSessionUserObj = {};
				let epoch = value.ls*1000;                           
                let id = common.timelyEventId(value.id, epoch);
                value.package = value.name.replace(/\./g, "_");
				//let data = fillCompetingAppsObjectWithEpoch(epoch,value.package,value.name, updateSessionUserObj, platform, "asl."+getAverageSessionUserKey(value.tsd));

				common.fillEventObjectWithEpoch(epoch, updateSessionUserObj, platform+"."+value.package, "sc."+common.getActiveUserKey(value.sc));

                common.fillEventObjectWithEpoch(epoch, updateSessionUserObj, platform+"."+value.package, "asl."+common.getAverageSessionUserKey(value.tsd));

				 resultArray.push({updateSessionUserObj: updateSessionUserObj, id: id})
			})
		}
	}
})


fillCompetingAppsObjectWithEpoch = function(epoch,package,name,object, platform, eventKey, increment){
        increment = (increment)? increment:1;
        let qDate = moment(epoch).format('YYYY_M_D');
        object[platform+"."+package+"."+qDate+"."+eventKey] = increment;
    }


if(resultArray.length > 0){
	logger.info(`resultArray ==>  ${resultArray.length}`)
    counter     = 0;
    updateCsessions(counter);
}

function updateCsessions(counter){
	if(resultArray[counter]){
		let id = resultArray[counter].id;
		let updateSessionUserObj = resultArray[counter].updateSessionUserObj;
		common.db.collection('timely_users_session').update({'_id': id}, {'$inc': updateSessionUserObj}, {'upsert': true},function(err, response){
            if(err){
				logger.info(`error =>> ${err}`);    
            }
            else{
				logger.info("inserted!");   
            }
			logger.info(`counter ==>  ${counter}`);
            counter++;
            updateCsessions(counter);
        });
	}
}

function getAverageSessionUserKey(tsd){
    if(tsd/60 > 5){
        return "5+";
    }
    else if(tsd/60 > 3 && tsd/60 <= 5){
        return "3-5";
    }
    else if(tsd/60 >= 1 && tsd/60 <= 3){
        return "1-3";
    }
    else if(tsd/60 >= .5 && tsd/60 <= 1){
        return "0:5-1";
    }
    else{
        return "<30";
    }
}
//Create a collection for competing apps which will store info like this//
/*let appsComps = [
	{
		"name" : "LimeRoad",
        "package" : "com.shopping.limeroad",
        "id" : "5710b0703ea9dc8806a261d0"
	},
	{
		"name" : "Voonik",
        "package" : "com.voonik.android",
        "id" : "57171cccc9023bab06619218",
	},
	{
		"name" : "craftsvilla",
        "package" : "com.craftsvilla.app",
        "id" : "571f3fea5782d9376b196e78"
	} 
]

appsComps.push({name:"session testing", id:"57c918de322e0bbf25a0bd0f"});

let array = [];
let query = {};
appsComps.forEach(function(item){
	fillCompetingAppsQueryObject(query, item.id, item.name, array, 1472668200, 1474396199.999, 'android', '57c918de322e0bbf25a0bd0f');
	fillCompetingAppsQueryObject(query, item.id, item.name, array, 1472668200, 1474396199.999, 'ios', '57c918de322e0bbf25a0bd0f');	
});

 


common.db.collection('timely_users_session').find({_id:{$in:array}}, query).toArray(function(error, result){
	if(!error){
		if(result && result.length > 0){
			let type = false;
			let data = prepareSessionData(result,type)

		}
	}
})


function fillCompetingAppsQueryObject(object, cId, cName, array ,epochStartDate_C, epochEndDate_C, platform, appId){
		let number = 1;
        let startDate_C = epochStartDate_C*1000;
        let endDate_C = epochEndDate_C*1000;
        endDate_C = moment(endDate_C).add(number,'days').format('YYYY-MM-DD');
        while(moment(startDate_C).valueOf() < moment(endDate_C).valueOf()){
            let year = moment(startDate_C).format('YYYY');
            let month = parseInt(moment(startDate_C).format('MM'));
            let day = parseInt(moment(startDate_C).format('D'));
            let qDate = year+"_"+month+"_"+day;
            object[platform+'.'+cName+'.'+qDate] = 1;
        	if(array.indexOf(common.timelyEventId(cId, startDate_C)) == -1){
                array.push(common.timelyEventId(cId, startDate_C));
            }
            startDate_C = moment(startDate_C).add(number,'days').format('YYYY-MM-DD');
        }
}

let prepareSessionData = function (data,type){
	let objData = { "android":{}, "ios":{} };
	let platforms = ['android','ios'];
    if(data){
        data.forEach(function(item){
        	platforms.forEach(function(platform){
        		if(item[platform] != undefined){
        			// get platform users app users
		    		let platformData = item[platform];
			        let apps = Object.keys(platformData);
			        apps.forEach(function(app){
			            if(objData[platform][app] == undefined){
			                objData[platform][app] = getSessionStructure(type);
			            }
			            let dates = Object.keys(platformData[app]);
			            dates.forEach(function(date){
			                if(type){
			            		if(platformData[app][date]['sc']){
			                    	addActiveUserData(platformData, app, date, platform, objData);
				                }	
			            	}
			            	if(platformData[app][date]['asl']){
			                	addAvrageUserData(platformData, app, date, platform, objData);
			                }
			            });
			        });
        		}

        	});        	
	    });
    }
     
    return objData;
}

function getSessionStructure(type){
    if(type == 'both'){
         return {
            "au":{
                "10+":0,
                "8-10":0,
                "6-8":0,
                "2-5":0,
                "1":0
            },
            "asl":{
                "5+":0,
                "3-5":0,
                "1-3":0,
                "0.5":0,
                "<30":0
            }
        } 
    }
    else{
        return {
                "asl":{
                    "5+":0,
                    "3-5":0,
                    "1-3":0,
                    "0.5":0,
                    "<30":0
                }
            } 
    }  
}

function addAvrageUserData(platformData, app, date, platform,objData){
    if(platformData[app][date]['asl']['5+']){
        objData[platform][app]['asl']['5+'] += platformData[app][date]['asl']['5+'];
    }
    if(platformData[app][date]['asl']['3-5']){
        objData[platform][app]['asl']['3-5'] += platformData[app][date]['asl']['3-5'];
    }
    if(platformData[app][date]['asl']['1-3']){
        objData[platform][app]['asl']['1-3'] += platformData[app][date]['asl']['1-3'];
    }
    if(platformData[app][date]['asl']['0.5']){
        objData[platform][app]['asl']['0.5'] += platformData[app][date]['asl']['0.5'];
    }
    if(platformData[app][date]['asl']['<30']){
        objData[platform][app]['asl']['<30'] += platformData[app][date]['asl']['<30'];
    }
}

function addActiveUserData(platformData, app, date, platform,objData){
    if(platformData[app][date]['sc']['10+']){
        objData[platform][app]['au']['10+'] += platformData[app][date]['sc']['10+'];
    }
    if(platformData[app][date]['sc']['8-10']){
        objData[platform][app]['au']['8-10'] += platformData[app][date]['sc']['8-10'];
    }
    if(platformData[app][date]['sc']['6-8']){
        objData[platform][app]['au']['6-8'] += platformData[app][date]['sc']['6-8'];
    }
    if(platformData[app][date]['sc']['2-5']){
        objData[platform][app]['au']['2-5'] += platformData[app][date]['sc']['2-5'];
    }
    if(platformData[app][date]['sc']['1']){
        objData[platform][app]['au']['1'] += platformData[app][date]['sc']['1'];
    }
}
*/











