let common = require('./../../utils/common.js');
let appsArray   = [];
let resultArray = [];
let counter     = 0;
const logger = require('../../../logger');

function updateEvents(counter){
    if(resultArray[counter]){
        let events_stats_obj = resultArray[counter].events_stats_obj;
        let id = resultArray[counter].id;
        common.db.collection('events_stats').update({'_id': id}, {'$inc': events_stats_obj}, {'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:{$in:['Campaign_Received','Campaign_Viewed','Campaign_Clicked','Campaign_Deleted']}},{'key':1, 'eventTime':1, 'campid':1, 'context':1}).toArray(function(error, result){
        if(!error){
            if(result){
                resultArray = [];
                logger.info(`result length :: +> ${result.length}`);
                result.forEach(function(event){
                    if(event.context && event.context.who && event.context.who.device && event.context.who.device.p && event.context.who.device.d && event.eventTime && event.key &&  event.context.where &&  event.context.where.geo && event.context.where.geo.cc && event.context.where.geo.cty && event.context.where.location && event.context.where.location.place){
                        if(event.context.who.device.p != undefined){
                            platform = event.context.who.device.p.toLowerCase();
                            let events_stats_obj = {};
                            let device = event.context.who.device.d;
                            let country = event.context.where.geo.cc;
                            let city = event.context.where.geo.cty;
                            let place = event.context.where.location.place;
                            common.fillCampaignEventObj(events_stats_obj, platform, event.eventTime, device, country, city, place, event.key);
                            //events_stats_obj[platform+"."+event.key] = 1;
                            resultArray.push({events_stats_obj: events_stats_obj, id:appId+event.campid})
                        }
                    }
                });
                logger.info(`result array length :: +> ${resultArray.length}`); 
                if(resultArray.length > 0){
                    counter = 0;
                    updateEvents(counter);
                }
            }
        }
    });
}

getEvents("57f7a1a9662688ff05897eb1");