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

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


let dataArray    = [];
let sessionArray = [];
let dataCounter  = 0;
let sessionCounter = 0;

function updateTimelySession(sessionCounter){
    logger.info(`sessionCounter ::: ${sessionCounter}`); 
    if(sessionArray[sessionCounter]){

        let appId = sessionArray[sessionCounter].appId;
        let updateSession = sessionArray[sessionCounter].updateSession;

        common.db.collection('timely_sessions').update({'_id': common.db.ObjectID(appId)}, {'$inc': updateSession}, {'upsert': true},function(err, response){
            if(err){
                logger.error(`error=> ${err}`);
            }
            else{
                logger,info("inserted!");    
            }
            sessionCounter++;
            updateTimelySession(sessionCounter);
        });
    }
    else{
        dataCounter++;
        getSessions(dataCounter);
    }
}

function getSessions(dataCounter){
    logger.info(`Data counter  :: +> ${dataCounter}`);
    if(dataArray[dataCounter]){
        sessionArray = [];
        sessionCounter = 0;
        sessionArray = dataArray[dataCounter].data;
        updateTimelySession(sessionCounter);
    }
    else{
        logger.info('completed single app record insertion') 
    }
}

function getAppUsers(appId){
	common.db.collection('app_users'+appId).find({},{'p':1,'sessions':1, 'tz':1}).toArray(function(err, result){
		if(!err){
            logger.info(`appid  :: +> ${appId}`);
            logger.info(`result.length :: +> ${result.length}`);
            dataArray = [];

            if(result.length > 0){                
                //result.forEach(function(value){
                result.forEach(function(value){

                    if( value.sessions ){            
                        let tmpArray = [];
                        logger.info(`session lenght :: +> ${value.sessions.length}`);
                        value.sessions.forEach(function(session){
                            session.p = (session.p)? session.p : 'other';

                            if(value.p && session.st && session.p ){
                                
                                //session.st = (value.tz)? session.st+parseInt(value.tz): session.st;
                                let updateSession  = {}, time = common.getDayTime(session.st);
                                platform = value.p.toLowerCase();
                                
                                common.fillTimeObjectWithEpoch(platform, session.st, updateSession, time+"."+session.p);
                                common.fillTimeObjectWithEpoch(platform, session.st, updateSession, time+".total");
                                common.fillTimeObjectWithEpoch(platform, session.st, updateSession, "total");
                                
                                tmpArray.push({appId:appId, updateSession:updateSession});
                            } 
                        });

                        if(tmpArray){
                            dataArray.push({data:tmpArray})
                        }
                    }
                });
                
                if(dataArray){
                    dataCounter = 0;
                    getSessions(dataCounter);
                }
                
            }
            else{
            	 
                counter++;
                getAppIds(counter);
            }
		}
	});
}

let appsArray   = [];
let counter     = 0;

function getAppIds(counter){
     
    if(counter < appsArray.length){
        getAppUsers(appsArray[counter]);
    }
    else{
    	return;
    }
}

function getApps(){
    //{"isAppDeleted":"false"}
    common.db.collection('apps').find({"isAppDeleted":"123false"},{'app_id':1}).toArray(function(err, result){
        if(!err){
            result.forEach(function(value){
                if( value.app_id ){
                    appsArray.push(value.app_id);
                }
            });
            appsArray.push("56fd14b8067fbebd385dd09c");
            if(appsArray.length > 0){
                getAppIds(counter);
            }
        }
    });
}

getApps();
