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 appsArray   = [];
let resultArray = [];
let counter     = 0;

function updateEvents(counter){

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

function getEvents(appId){
    common.db.collection('events_'+appId).find({},{'key':1, 'eventTime':1, 'context.who.device.p':1}).toArray(function(error, result){
        if(!error){
            if(result){
                logger.info(`result.length :: +> ${result.length}`);
                resultArray = [];
                result.forEach(function(value){

                    if(value.context && value.context.who && value.context.who.device && value.context.who.device.p && value.eventTime && value.key ){
                        if(value.context.who.device.p != undefined){
                            platform = value.context.who.device.p.toLowerCase();
                            let epoch = value.eventTime*1000;                           
                            let id = common.timelyEventId(appId, epoch);
                            
                            let updateEventsObj = {};
                            common.fillEventObjectWithEpoch(epoch, updateEventsObj, platform, value.key);
                            common.fillEventObjectWithEpoch(epoch, updateEventsObj, platform, "total");
                            
                            resultArray.push({updateEventsObj: updateEventsObj, id: id})
                        }
                    }
                });
                logger.info(`resultarray.length :: +> ${resultArray.length}`);
                if(resultArray.length > 0){
                    counter     = 0;
                    updateEvents(counter);
                }
            }
        }
    });
}

getEvents("575e36c737c678730603d70f");

/*function getAppIds(counter){
     
    if(counter < appsArray.length){
        getEvents(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("56d7df2c1d4de4fe1a902786");
            if(appsArray.length > 0){
                getAppIds(counter);
            }
        }
    });
}

getApps();*/