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

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

/*function updateEpochRec(epochCounter){
    if(updateEpoch[epochCounter]){
        let history = updateEpoch[epochCounter].history;
        let id = updateEpoch[counter].id;
        let appId = updateEpoch[counter].appId;
        common.db.collection('app_users'+appId).update({'_id': id}, {'$set': {"history":history}},function(err, response){
            if(err){
                 
            } else{
                 
            }
             
            epochCounter++;
            updateEpochRec(epochCounter);
        });
    } else{
         
    }
}*/

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}`);
                logger.info(`id  :: +> ${id}`);
            } else{
                 
            }
             
            counter++;
            updateInstallUninstsll(counter);
        });
    } else{
        logger.info("done optimization!");
        appCounter++;
        getAppIds(appCounter);
        //updateEpochRec(epochCounter);
    }
}

function getAppUsers(appId){
    logger.info(`app_users = > ${appId}`);
    //fs:{$gte:1467570600, $lte:1467743399.999}
    common.db.collection('app_users'+appId).find({fs:{$gte:1467892872, $lte:1468411112}},{'_id':1,'pv':1, 'av':1, 'history':1, "p":1, 'tz':1, 'cc':1, 'cty':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){
                     
                    if(value.pv && value.av && value.p && value.cc && value.cty
                        && value.history && value.history.length > 0 && value.history[0].dtEntry && value.history[0].refname 
                        ){
                        let historyArray = [];
                        value.history.forEach(function(history, hKey){
                            if(history.refname){
                                let platform = value.p.toLowerCase();
                                history.dtEntry = (value.tz)? history.dtEntry+parseInt(value.tz): history.dtEntry;
                                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.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);
                                }                       

                                if(history.type == "U" && value.history[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");
                                    }

                                    // get install
                                    let history = value.history[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(history.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;
                                    common.fillHistoryObjectWithEpoch(epoch, dashboardObj, platform, value.pv+"."+value.av+"."+history.refname+"."+value.cc+"."+value.cty+"."+diff);

                                }
                                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");
                                    }
                                }

                                if(Object.keys(dashboardObj).length != 0){
                                    resultArray.push({dashboardObj: dashboardObj, id: id});
                                }
                            }                            
                        }); 

                        if(historyArray.length > 0 ){
                            updateEpoch.push({appId:appId, id:value._id, history: historyArray});
                        }
                                                                 
                    }
                    else{
                        logger.info(`c==> ${c}`);
                        c++;
                    }
                });
                logger.info(`resultArray.length ==> ${resultArray.length}`);
                if(resultArray.length > 0){
                    counter = 0;
                    updateInstallUninstsll(counter);
                }
                else{
                    appCounter++;
                    getAppIds(appCounter);
                }
            }
        }
        else{
            logger.error(`error ==> ${error}`); 
        }
    });
}

let getAppIds = function(appCounter){
    if(appsArray[appCounter]){
        getAppUsers(appsArray[appCounter]);
    }
    else{
        logger.info("complete optimization!!"); 
    }
}

/*appsArray = [
            '574bc887b794654d042aac89',
            '5719e6e2e0e4e57109945027',
            '56d147239534b80b22ebbb86',
            '5677b8fc37ef5bcc44000001',
            '562f387d58f26fd54c00030c',
            '56c1cfff06ccc9cd552aa4f0',
            '56c1cf435f7744cc550a25f2',
            '56266551a64a78b40e000bd0',
            '5608cf9168f71da90f000018',
            '55ddb516ce8512a10f000017'
        ];*/

getAppIds(appCounter);
