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

let resultArray = [];
let appId = "5ad83ce1f71de7016db4c0c1";
let counter = 0;

function updateInstallUninstsll(counter){
    if(resultArray[counter]){
        let campaignObj = resultArray[counter]
        // dump campaign installs and uninstalls
        common.db.collection('campaign_aggregate').update({'_id': common.db.ObjectID(appId)}, {'$inc': campaignObj}, {'upsert': true},function(err, response){
            if(err){
                logger.error(`error=> ${err}`); 
            } else{
                logger.info(`data inserted into campaign_aggregate!  :: +> ${counter}`);
                updateInstallUninstsll(++counter)
            }
        });
    } else{
        logger.info("done optimization!");
        process.exit(1);
    }
}

function getAppUsers(){
    logger.info(`app_users  :: +> ${appId}`);
    //fs:{$gte:1459449000, $lt:1464719399}
    common.db.collection('app_users'+appId).find({fs:{$lt:1527759141}},{'_id':1,'history':1,"p":1}).toArray(function(error, result){
        if(!error){
            if(result){
                logger.info(`result  :: +> ${result.length}`);
                resultArray = [];
                let c = 1;
                let count=1;

                result.forEach(function(value, key){
                    value.history.forEach(function(history, hKey){
                        let platform = value.p.toLowerCase();
                        if(history.utm_campaign){
                            // replace dot if exists into campapign string
                            history.utm_campaign = history.utm_campaign.replace(/\./g, "-");
                            // manage campaign aggregate collection
                            let campaignObj = {};
                            if(history.type == 'I'){
                                // add cpi avg
                                if(history.cpi){
                                    common.fillEventObjectWithEpoch(history.dtEntry*1000, campaignObj, platform, history.utm_campaign+".cpi", history.cpi);
                                }
                                if(history.isnew == true){ // unique install
                                    common.fillEventObjectWithEpoch(history.dtEntry*1000, campaignObj, platform, history.utm_campaign+".in");
                                }else{ // repeat install
                                    common.fillEventObjectWithEpoch(history.dtEntry*1000, campaignObj, platform, history.utm_campaign+".ri");
                                }
                            }
                            else if(history.type == 'U'){
                                 let refObj = value.history[hKey-1];
                                 //history.dtEntry = (value.tz)? history.dtEntry+parseInt(value.tz): history.dtEntry;
                                 let uninstallDate = moment(history.dtEntry*1000).format('YYYY-MM-DD');
                                 let installDate = moment(refObj.dtEntry*1000).format('YYYY-MM-DD');
                                 let diff = moment(uninstallDate).diff(moment(installDate), 'days', true);
                                 diff = parseInt(Math.abs(diff));
                                 diff = (diff == 0)? 'o' : diff;
                                 // store uninstall days difference
                                 common.fillEventObjectWithEpoch(history.dtEntry*1000, campaignObj, platform, history.utm_campaign+"."+diff);
                                 if( history.isnew){ // unique uninstall
                                    common.fillEventObjectWithEpoch(history.dtEntry*1000, campaignObj, platform, history.utm_campaign+".un");
                                 }else{ // repeat uninstall
                                    common.fillEventObjectWithEpoch(history.dtEntry*1000, campaignObj, platform, history.utm_campaign+".ru");
                                 }
                            }
                            resultArray.push(campaignObj);
                        }
                    });
                });
                logger.info(`resultArray.lenght  :: +> ${resultArray.length}`);
                if(resultArray.length > 0){
                    counter = 0;
                    updateInstallUninstsll(counter);
                }
            }
        }
    });
}

getAppUsers();
