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

let resultArray = [];
let counter     = 0;
let epochCounter = 0;
let updateEpoch = [];

function updateInstallUninstsll(counter){
    if(resultArray[counter]){
        let dashboardObj = resultArray[counter].dashboardObj;
        let id = resultArray[counter].id;
        common.db.collection('timely_dashboard').update({'_id': id}, {'$inc': dashboardObj}, {'upsert': true},function(err, response){
            if(err){
                logger.error(`error=> ${err}`); 
            } else{
                logger.info(`${counter} inserted!:: ${response}`);       
            }
             
            setTimeout( ()=> {
                counter++;
                updateInstallUninstsll(counter);
            }, 0);
        });
    } else{
        logger.info("done optimization!");
        process.exit(1);
    }
}
// 1546848357+19800
let inCount = 0;
let unInCount = 0;
function getAppUsers(appId){
    logger.info(`app_users'::  ${appId}`);
    //fs:{$gte:1459449000, $lt:1464719399} fs:{$gte:1500921000,$lt:1501007399}
    common.db.collection('app_users'+appId).find({"p":"Android"},{'_id':1,'pv':1, 'av':1, 'history':1, "p":1, 'tz':1, 'cc':1, 'cty':1}).toArray(function(error, result){
        if(!error){
            if(result){
     
                resultArray = [];
                let c = 1;
                let count=1;
                result.forEach(function(value, key){
   
                    if(value.pv && value.av && value.p && value.cc && value.cty
                        && value.history && value.history.length > 0 ){
                        let historyArray = [];
 
                        let x =value.history;
                        logger.info(typeof (x));
                        if(typeof (x) == 'string'){    
                            a = x.replace(/\\"/g, '"');
                            let data = a.split();
                        }else{
                            let data=x;
                        }
                        data.forEach(function(history, hKey){
                           // if(history && history.dtEntry && history.refname){
                            //if(history.refname && history.dtEntry >= 1459449000 && history.dtEntry <= 1464719399){
                                let platform = value.p.toLowerCase();
                                //if(history.refname && history.dtEntry >=1459449000 && history.dtEntry <1462041000){
                                let platform = value.p.toLowerCase();
                                historyArray.push(history);
                                let dtEntry = history.dtEntry;
                                let epoch = history.dtEntry*1000;
                                let id = common.timelyEventId(appId, epoch);
                                // value.pv = value.pv.replace(/\./g, "_");
                                // value.pv = value.pv.replace(/\:/g, "_");
                                // value.av = value.av.replace(/\./g, "_");
                                // value.av = value.av.replace(/\:/g, "_");
                                // history.refname = history.refname.replace(/\./g, "-");
                                // value.cty = value.cty.replace(/\./g, "-");
                                // value.cc = value.cc.replace(/\./g, "-");
                                let dashboardObj = {};
                                let cpi = (history.cpi)? history.cpi : 0;

                                // add cpi
                                /*if(cpi && cpi > 0){
                                    common.fillHistoryObjectWithEpoch(epoch, dashboardObj, platform, value.pv+"."+value.av+"."+history.refname+"."+value.cc+"."+value.cty+".cpi", cpi);
                                }
                                */
                                logger.info(`history ${history}`);
                                // if(history.type == "U" && data[hKey-1].type == 'I'){ // get uninstall
                                    
                                    if(history.isnew == true){ // unique uninstall
                                        common.fillHistoryObjectWithEpoch(epoch, dashboardObj, platform, value.pv+"."+value.av+"."+history.refname+"."+value.cc+"."+value.cty+".un");
                                    }else{ // repeat uninstall
                                        common.fillHistoryObjectWithEpoch(epoch, dashboardObj, platform, value.pv+"."+value.av+"."+history.refname+"."+value.cc+"."+value.cty+".ru");
                                    }
                                    // fill total uninstalls
                                    common.fillHistoryObjectWithEpoch(epoch, dashboardObj, platform, "totalUn", 1, false);

                                    // get install
                                    let history = data[hKey-1];
                                    //history.dtEntry = (value.tz)? history.dtEntry+parseInt(value.tz): history.dtEntry;
                                    let uninstallDate = moment(dtEntry*1000).format('YYYY-MM-DD');
                                    let installDate = moment(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;
                                    // manage cohort
                                    dashboardObj[platform + "." + moment(epoch).format("YYYY_M_D") + ".cohort." + diff] = 1;
                                    common.fillHistoryObjectWithEpoch(epoch, dashboardObj, platform, value.pv+"."+value.av+"self"+value.cc+"."+value.cty+"."+diff);
                                    unInCount++;
                                // }
                                // else if(history.type == "I"){ // get install
                                //     if(history.isnew == true){ // unique install
                                //         common.fillHistoryObjectWithEpoch(epoch, dashboardObj, platform, value.pv+"."+value.av+"."+history.refname+"."+value.cc+"."+value.cty+".in");
                                //     }else{ // repeat install
                                //         common.fillHistoryObjectWithEpoch(epoch, dashboardObj, platform, value.pv+"."+value.av+"."+history.refname+"."+value.cc+"."+value.cty+".ri");
                                //     }
                                //     // manage cohort
                                //     dashboardObj[platform + "." + moment(epoch).format("YYYY_M_D") + ".cohort.in"] = 1;
                                //     inCount++;
                                //     // fill total installs
                                //     common.fillHistoryObjectWithEpoch(epoch, dashboardObj, platform, "totalIn", 1, false);
                                // // }

                                // if(Object.keys(dashboardObj).length != 0){
                                //     resultArray.push({dashboardObj: dashboardObj, id: id});
                                // }
                          // }
                           // }
                        });
                    }
                    else{
                        logger.info(`value.id :::>>> ${value._id} :: c==>>  ${c}`) 
                        c++;
                    }
                });
                logger.info(`resultArray  :: +> ${resultArray.length}`);
                logger.info(`inCount  :: +> ${inCount}`);
                logger.info(`unincount  :: +> ${unInCount}`);
                if(resultArray.length > 0){
                    counter = 0;
                    updateInstallUninstsll(counter);
                }
            }
        }
    });
}

getAppUsers("5d5fd1290200e5b6009d6478");
