/**
* ==============================================
* Check and update expired campaigns of all apps
* ==============================================
*
* 1. Use getAllAppsIds function for get all active app ids. This will return app ids in callback function.
* 2. Use updateCampaigns for check expired campaign and update campaign status and remove from cache as well.
*
* @copyrights All right reserved by appice.io.
**/
var campaigns = {},
    common = require('./../../utils/common.js'),
    logger = require('../../../logger'),
    semusiConfig = require('./../../config'),
    cacheApi = require('./../../utils/semusi.cache.js'),
    moment = require('moment'),
    async = require('async');
    //request = require('request');
  



(function (campaigns) {
    // get all apps ids
    campaigns.getAllAppsIds = function(callback){
        //isAppDeleted:"true"
        common.db.collection('apps').find({isAppDeleted:"false"},{_id:1,key:1}).toArray(function (err, appIds){
            if(err){
                logger.error(`error => ${err}`);
                callback(err, null);
            }
            else{
                 //campaigns.updateCampaigns(appIds);
                callback(null,appIds);
            }
        });
    }

    // update campagins
    campaigns.updateCampaigns =  function(appIds){        
        for (var i = 0; i < appIds.length; i++) {
            (function(i){
                setTimeout(function(){
                        common.db
                        .collection('campaigns_'+appIds[i]._id)
                        .find({"st":{ $in: ["PENDING","ACTIVE","DRAFT"] },"d":false})
                        .toArray(function(err, cmpData) {
                           if(cmpData.length > 0){
                                var currentDate = moment().unix()*1000;
                                cmpData.forEach(function(cmp) {
                                    
                                    if(cmp.sd < currentDate && currentDate < cmp.ed){
                                        
                                        let st = new Date(cmp.sd);   // start time fatch start hour
                                        let ct = new Date();     // current time for fatch current hour
                                        let et = new Date(cmp.ed); // start time fatch end hour
                                        // dayMatchForCmp function call for day validation cmp
                                        let daymatch  = dayMatchForCmp(cmp.days,ct.getDay());
                                        if(daymatch){ 
                                            if(st.getHours() <= ct.getHours() && ct.getHours() <= et.getHours()){
                                                if(cmp.st == 'PENDING'){
                                                        let args = {"a":true,"ud":currentDate,"st":"ACTIVE","segmentname":cmp.segmentname,"segmentinfo":cmp.segmentinfo}
                                                        let api_key = appIds[i]._id;
                                                        let cid = cmp._id;
                                                        let app_id = appIds[i]._id;
                                                        //let baseURL = 'https://panel.appice.io';
                                                        let baseURL = semusiConfig.cdnUrl;
                                                        
                                                        //URL for run campaign using panel setActive api 
                                                        var URL = baseURL+"/i/templates/setActiveCampaign?callback=jQuery19109514835126252086_1585556222503&args="+JSON.stringify(args)+"&api_key="+api_key+"&cid="+cid+"&app_id="+app_id+"&_=1585556222510";
                                                        request(URL, function (error, response, body) {     
                                                            logger.error(`error => ${error}`); // Print the error if one occurred
                                                            logger.info(`statusCode: ${response && response.statusCode}`);
                                                            logger.info(`body: ${body}`); // response.                                                   
                                                             
                                                            return response;
                                                        });
                                                    }  
                                                }else{
                                                    if(cmp.st == 'ACTIVE'){
                                                        logger.info(`++++++ active else ++++++`);
                                                        // update cmp Active to pending to run next day
                                                        cmpStatusUpdate(appIds[i]._id,cmp._id,"PENDING");
                                                        logger.info(`++++++ after update else ++++++`);
                                                        common.deleteCampaignCache(appIds[i]._id, cmp._id);
                                                    }
                                                }            
                                        }else{
                                            if(cmp.st == 'ACTIVE'){
                                                logger.info(`active`);
                                                // update cmp Active to pending to run next day
                                                cmpStatusUpdate(appIds[i]._id,cmp._id,"PENDING");
                                                common.deleteCampaignCache(appIds[i]._id, cmp._id);
                                                return "cmpStatusUpdate : PENDING";
                                            }
                                        }
                                    }else{
                                        cmpStatusUpdate(appIds[i]._id,cmp._id,"PAST");
                                        common.deleteCampaignCache(appIds[i]._id, cmp._id);
                                    }
                                });
                           }
                        });
                        if(i+1 == appIds.length){
                            process.exit(1);
                        }
                    }, 1000 * (i + 1));
                })(i);
        }
    }

    function getCampaignDatawithcid(app_id) {
        logger.info(`PostData data does not contain data object+> ${app_id}`);
        return new Promise(function(resolve, reject) {
            var query = {"st":{ $in: ["PENDING","ACTIVE","DRAFT"] },"d":false};

            var result = common.db.collection("campaigns_"+app_id).find(query).toArray();
                
            setTimeout(function() {
                resolve(result);
            }, 100000);
        });
    }

    // check campaigns
    campaigns.checkCampaigns = function(){
        campaigns.getAllAppsIds(function(err, appIds){
            logger.error(`error => ${err}`);
             
            if(err){
                logger.error(`error:: apps not found => ${err}`);
                process.exit(1); 
            }
            else{
                campaigns.updateCampaigns(appIds); 
            }
        });
    }

    // Day match function for campaign run  BY dushyant 
    var dayMatchForCmp = function(days,today){
        let match = false;
        days.forEach(function(item){
            if(item == today) match =  true;
        });
        return match;  
    }
    // common function for campaign update BY dushyant
    var cmpStatusUpdate = function(app_id,cid,status){
            activeCampaign = {};
            activeCampaign['updatedAt'] = common.getCurrentEpochTime();
            activeCampaign.st = status;
            common.db.collection('campaigns_'+app_id).update({'_id': common.db.ObjectID(cid)}, {$set: activeCampaign}, {safe: true}, function(err, isOk) {
                if(!err){
                    logger.info(`updated`);  
                    
                }else{
                    logger.error(`error => ${err}`);   
                }
            });
    }

}(campaigns));

campaigns.checkCampaigns();


