let common = require('./../../utils/common.js');
const logger = require('../../../logger');

let resultArray = [];
let appCounter = 0;
let Count = 0;
let limit = 0;
let skip = 0;
let loop = 0;
let res = [];

function competingAppsCollection(competingObj, appid) {
    logger.info(`competingObj =>  ${competingObj}`)
    common.db.collection('competing_aggregates').update({
        '_id': common.db.ObjectID(appid)
    }, {
        $set: competingObj
    }, {
        'upsert': true
    }, function(err, app) {
        if (err) {
            logger.error(`error=> ${err}`);   
        }
        logger.info('update one app');
        if (res.length > 0) {
            res = [];
            logger.info(`emptied array ${res}`);  
        }
        res = [];
        appCounter++;
        getApp();
    });
}

function getAppUsers(appId){
  
            if(res.length > 0){
             
                let competingObj = {
                    android:{
                        ctr:{

                        },
                        comp:{
                            

                        }
                    },
                    ios:{
                        ctr:{

                        },
                        comp:{
                            
                        }
                    }
                };

                let competingNewObj = {}
                let isCompetingApps = false;
              
                res.forEach(function(value){
                  value.forEach(function(value){
                    if(value.p != null && value.p != undefined){
                        let platform = value.p.toLowerCase();
                    }
                    if(platform !== undefined){
                        if(value.competingapps && value.competingapps.apps){
                     
                        // manage completing apps user with competing apps count wise
                        if(competingObj[platform]['ctr'][value.competingapps.apps.length] === undefined){
                            competingObj[platform]['ctr'][value.competingapps.apps.length] = 1;
                            
                        }
                        else{
                            competingObj[platform]['ctr'][value.competingapps.apps.length] += 1;
                           
                        }


                        // manage competing app unique users count
                        value.competingapps.apps.forEach( competing => {
                         
                            if(competing && competing.name){
                              
                                if(competingObj[platform]['comp'][competing.name] === undefined){
                                 
                                    competingObj[platform]['comp'][competing.name] = 1;
                                }
                                else{
                              
                                    competingObj[platform]['comp'][competing.name] += 1;
                                }
    
                                //competingNewObj[platform +".comp."+competing.name] = competingObj[platform]['comp'][competing.name];
                                isCompetingApps = true;
                            }
                        })
                    }
                }
                });
            });

            logger.info(`competingObj =>${competingObj}`);
                if(isCompetingApps){
                    competingAppsCollection(competingObj, appId);
                }
                else{
                    appCounter++;
                    getApp();
                }
            } 
            else{
                appCounter++;
                getApp();
            }
       
        
  


}

 function getAppUserCount(appid,callback){
    
   common.db.collection('app_users'+appid).find({active:true},{'_id':0, "p":1, 'competingapps':1}).count(function(err,count){
        if(err){
            appCounter++;
             getApp();
        }
        if(!err && count){
            Count = count;
        
            if(count >= 100000){
                limit = Math.round(Count/20);
            }
            else if(count >= 50000 && count < 100000){
                limit = Math.round(Count/4);
            }
            else{
                limit = count;
            }
            callback(appid,count)
        }
        else{
            appCounter++;
            getApp();
        }
     
    });

}

function processCount(appId,count)
{

    common.db.collection('app_users'+appId).find({active:true},{'_id':1, "p":1, 'competingapps':1}).skip(skip).limit(limit).toArray(function(error, result){
        if(error){
            return getAppUsers(common.config.intetestAppsList[appCounter]);

        }
        if(!error && result){
            res.push(result);
            skip+=limit;
            loop+=limit;
            if(loop < count){
               return processCount(appId,count);
            }else{
          
                skip=0;
                limit=0;
                loop=0;
                return getAppUsers(common.config.intetestAppsList[appCounter]);

            }
            
        }
    })


}




function getApp() {
    logger.info(`appCounter => ${appCounter}`)
    if(common.config.intetestAppsList[appCounter]){
      getAppUserCount(common.config.intetestAppsList[appCounter], processCount);  
    }
    else {
        logger.info('done processs!');
          process.exit(1);
    }
}

getApp();
