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

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

let appsGroups = [
	{
		"name":"Group One",
		"list":[
			{
	            "state" : "I",
	            "name" : "LimeRoad",
	            "package" : "com.shopping.limeroad",
	            "id" : "5710b0703ea9dc8806a261d0",
	            "ls" :1473631301
	        }, 
	        {
	            "state" : "I",
	            "name" : "Voonik",
	            "package" : "com.voonik.android",
	            "id" : "57171cccc9023bab06619218",
	            "ls" : 1473739301
	        }
		]
	},
	{
		"name" : "Group Two",
		"list":[  
	            {
	                "state" : "I",
	                "name" : "craftsvilla",
	                "package" : "com.craftsvilla.app",
	                "id" : "571f3fea5782d9376b196e78",
	                "ls" : 1473372101
	            }
	        ]
	}

];
let appUsers = [
	{"_id":"57c918de322e0bbf25a0bd0f20169",
		"android":{
			"syncNscan":{
				"2016_9_3":
					{"sc":{"10+":2},
						"asl":{"5+":2}
					},
				"2016_9_2":
					{"sc":{"1":1,"6-8":1,"2-5":1},
						"asl":{"5+":1,"1-3":2}
					},
				"2016_9_6":{"sc":{"2-5":1},
					"asl":{"1-3":1}
				}
			}
		}
	}
];



let resultArray = [];
let counter = 0;
let idArr = []
let dataArr = [];
function groupList(counter){
    if(appsGroups[counter]){
		logger.info(`counter ==>> ${counter}`)
        appsGroups[counter].list.forEach(function(item){
            let epoch = item.ls*1000;                           
            let id = common.timelyEventId(item.id, epoch);
            idArr.push(id)
        });
        if(idArr.length > 0){            
            let groupObj = {};
            findTimelySessionUsers(idArr,function(data){
                if(data){
                    idArr = [];
                    groupObj.name = appsGroups[counter].name
                    groupObj.data = data;
                    dataArr.push(groupObj)
                }
                counter++;
                groupList(counter);                
            })
        }else{
            counter++;
            groupList(counter);
        }
    }else{
    	 
    	dataArr.push(appUsers)
        
        if(dataArr.length > 0){
        	generateGroupData(dataArr)
        }
        if(appUsers.length > 0){
        	generateAppUsersData(appUsers)
        }
       /* let id = ["57c918de322e0bbf25a0bd0f20169"];
    	common.db.collection('timely_users_session').find({_id:{$in:id}}).toArray(function(err, response){
	        if(err){
	             
	            callback([{custom:'data'}]);
	        }
	        else{
	        	 
	        	dataArr.push(groupObj)
	           generateGroupData(dataArr)
	        }
	    });*/    
    }    
}
/*if(counter > 0){
    findTimelySessionUsers()    
}*/

function findTimelySessionUsers(idArr,callback){
    common.db.collection('timely_users_session').find({_id:{$in:idArr}}).toArray(function(err, response){
        if(err){
			logger.error(`error => ${err}`);
            callback([{custom:'data'}]);
        }
        else{
            callback(response);
        }
    });
}

groupList(counter);

function generateGroupData(result){
	if(result && result.length > 0){
		let sessionKeys = {}
		let platforms = ['Android', 'IOS'];
		let counter = 0;
		let data = [];
		platforms.forEach(function(value){
			result.forEach(function(item,index){	
				if(item.data && item.data.length > 0){
					item.data.forEach(function(keyObj){	
						if(keyObj[value] != undefined){
	                    	let appNameKey = Object.keys(keyObj[value]);
	                    	appNameKey.forEach(function(appName){
	                    		let dayKeys = Object.keys(keyObj[value][appName]);
	                    		dayKeys.forEach(function(dayVal){
	                    			let avrageSlength = Object.keys(keyObj[value][appName][dayVal]);
	                    			avrageSlength.forEach(function(val){
	                    				let avSval = Object.keys(keyObj[value][appName][dayVal][val]);
	                    				avSval.forEach(function(avSessKey){
	                    					/*if(value.toLowerCase() == "android"){
	                    						if(val == "5+"){
	                    							sessionKeys.v += keyObj[value][appName][dayVal][val][v]
	                    						}
	                    					}*/
	                    				})
	                    			})	                    			
	                    		})
	                    	})
	                    	
                		}
					})					
				}
				if(data.indexOf(item.name) == -1){
					data.push({name:item.name});
					
				}
			})
		})		
	}
	logger.info(`aOneToThreeSession ==>> ${aOneToThreeSession}`)
	logger.info(`afivePlusSession ==>> ${afivePlusSession}`)	  
}

function generateAppUsersData(appsData){
	if(appsData.length > 0){
		let afivePlusSession = 0;
		let athreeToFiveSession = 0;
		let azeroPointFiveOne = 0;
		let aOneToThreeSession = 0;
		let alessThanThirtySeconds = 0;
		let ifivePlusSession = 0;
		let ithreeToFiveSession = 0;
		let izeroPointFiveOne = 0;
		let iOneToThreeSession = 0;
		let ilessThanThirtySeconds = 0;
		let platform = ['android', 'ios'];
		appsData.forEach(function(apps){
			let appName = Object.keys(apps);
			logger.info(`appName => ${appName}`)
			appName = appName.filter(function(n){ return n != "_id" });			
			platform.forEach(function(value){
				if(apps[appName][value] != undefined){
					//if(value == 'Android'){
						//value = value.toLowerCase()
						let dayKeys = Object.keys(apps[appName][value]);
						dayKeys.forEach(function(avrageSession){
							let aSession = Object.keys(apps[appName][value][avrageSession]);
							aSession.forEach(function(val){
								if(val == 'asl'){
									let aSVal = Object.keys(apps[appName][value][avrageSession][val]);
									aSVal.forEach(function(v){
										if(value == 'android'){
											if(v == '5+'){
												afivePlusSession += apps[appName][value][avrageSession][val][v];
											}
											if(v == '3-5'){
												athreeToFiveSession += apps[appName][value][avrageSession][val][v];
											}
											if(v == '0.5-1'){
												azeroPointFiveOne += apps[appName][value][avrageSession][val][v];
											}
											if(v == "1-3"){
												aOneToThreeSession += apps[appName][value][avrageSession][val][v];
											}
											if(v == "< 30"){
												alessThanThirtySeconds += apps[appName][value][avrageSession][val][v];
											}
										}
										if(value == 'ios'){
											if(v == '5+'){
												ifivePlusSession += apps[appName][value][avrageSession][val][v];
											}
											if(v == '3-5'){
												ithreeToFiveSession += apps[appName][value][avrageSession][val][v];
											}
											if(v == '0.5-1'){
												izeroPointFiveOne += apps[appName][value][avrageSession][val][v];
											}
											if(v == "1-3"){
												iOneToThreeSession += apps[appName][value][avrageSession][val][v];
											}
											if(v == "< 30"){
												ilessThanThirtySeconds += apps[appName][value][avrageSession][val][v];
											}
										}
									})
								}
							})
						})
					
				}
			});
		})
	}
}