/**
* ==============================================
* 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.
*
* @Author Manish Yadav
* @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 is => ${err}`);
                callback(err, null);
            }
            else{
                 //campaigns.updateCampaigns(appIds);
                callback(null,appIds);
            }
        });
    }

    // update campagins
    campaigns.updateCampaigns =  function(appIds){
        var i = 1;
        var appIdLenght = appIds.length;
        for (const app of appIds) {
            try {
                //Step 1: declare promise
                var cmpPromise = () => {
                return new Promise((resolve, reject) => {
                    common.db
                    .collection('campaigns_'+app._id)
                    .find({"st":{ $in: ["PENDING","ACTIVE","DRAFT"] },"d":false})
                    .toArray(function(err, data) {
                        err 
                            ? reject(err) 
                            : resolve(data);
                        });
                    });
                };
                //Step 2: async promise handler
                var callCmpPromise = async () => {
                    var cmpData = await (cmpPromise());
                    //camppaign send/update logic here is executed after result is resolved
                    if(cmpData.length > 0){
                        cmpData.forEach(function(cmp) {
                            common.deleteCampaignCache(app._id, cmp._id);
                        });
                    }else{
                        return "Campaign Not Found";
                    }
                };
                //Step 3: make the final call
                callCmpPromise().then(function(result) {
                   logger.info(`result=> ${result}`);   
                    i++;
                    if(appIdLenght == i){
                        process.exit(1);
                    }
                });
            }catch (err) {  
                logger.error(`error =>> ${err}`);
        }
    }

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

} 

}(campaigns))

campaigns.checkCampaigns();




