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 interestsCollection(interestsObj, appid){
    logger.info(`interestsObj ==> ${interestsObj}`);
    common.db.collection('interests_aggregates').update({'_id': common.db.ObjectID(appid)}, {$set : interestsObj}, { '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){
    logger.info(`app_users==> ${appId}`);
    
            if(res.length > 0){
               
            
                let interestsObj = {
                    android:{

                    }
                };

                let interestsNewObj = {}
                let isInterest = false;
                res.forEach(function(value){
                    value.forEach(function(value){
                    if(value.p != null){
                      let platform = value.p.toLowerCase();
                    }
                   if(platform !== undefined){ 
                    if(value.Interests && value.Interests !== undefined){
                        logger.info(`value . intrest::>> ${value.interests}`); 
                        value.Interests.forEach( interest=>{
                            if(interest && interest!==undefined){
                                logger.info(`intrest::>> ${interest}`);
                            if(interestsObj[platform][interest] === undefined){
                                interestsObj[platform][interest] = 1;
                            }
                            else{
                                interestsObj[platform][interest] += 1;
                            }
                        }
                      

                            //interestsNewObj[platform +"."+interest] = interestsObj[platform][interest];
                            isInterest = true;
                        })
                    }
                }
                });
            });

            logger.info(`interestsObj => ${interestsObj}`); 
                if(isInterest){
                    interestsCollection(interestsObj, appId);
                }
                else {
                    appCounter++;
                    getApp();
                }
            }
            else{
                appCounter++;
                getApp();
            }
     
 
}

function getAppUserCount(appid,callback){
    
    common.db.collection('app_users'+appid).find({active:true},{'_id':0, "p":1, 'Interests':1}).count(function(err,count){
      
         if(!err && count){
            logger.info(`count from getAppUserCount=>> ${count}`);
             Count = count;
         
             if(count >= 100000){
                 limit = Math.round(Count/20);
             }
             else if(count >= 50000 && count < 100000){
                 limit = Math.ceil(Count/4);
             }
             else{
                 limit = count;
             }
             callback(appid,count)
         }
         else{
             appCounter++;
             getApp();
         }
      
     });
 
 }
 
 function processCount(appId,count)
 {
    logger.info(`count :: +> ${count}`);
    logger.info(`skip  :: +> ${skip}`);
    logger.info(`loop  :: +> ${loop}`);
    logger.info(`limit :: +> ${limit}`);
     common.db.collection('app_users'+appId).find({active:true},{'_id':0, "p":1, 'Interests':1}).skip(skip).limit(limit).toArray(function(error, result){
         if(error){
            logger.error(`error in process count=> ${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{
                logger.info("Inside else block") 
                 skip=0;
                 limit=0;
                 loop=0;
                 return getAppUsers(common.config.intetestAppsList[appCounter]);
 
             }
             
         }
     })
     logger.info(`res array ${res}`);
 
 }
 

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();
