var campaignsApi = {},
    common = require('./../../utils/common.js'),
    fs = require('fs');
    GCM = require("gcm").GCM; 
    pushApi = require('./../../utils/pushApi.js');

(function (campaignsApi) {

    campaignsApi.getAllCampaigns = function (params) {        
        common.db.collection('campaigns'+params.qstring.args.app_id).find({}).toArray(function (err, campaigns) {
            let campaignsObj = packcampaigns(campaigns);
            common.returnOutput(params, campaignsObj);
            return true;
        });
        return true;
    };


    campaignsApi.createCampaign = function (params) {
         let argProps = {
                'name':     { 'required': true, 'type': 'String' },
                'pushtype': { 'required': true, 'type': 'String' },
                'content': { 'required': false, 'type': 'JSON' },              
                'expires': { 'required': false, 'type': 'String' }                
            },
            newCampaign = {};

        if (!(newCampaign = common.validateArgs(params.qstring.args, argProps))) {
            common.returnMessage(params, 400, 'Not enough args');
            return false;
        }

        newCampaign.expires = new Date(newCampaign.expires);
        newCampaign['createdAt'] = common.getCurrentEpochTime();
        //add the createdAt and updatedAt field        
        common.db.collection('campaigns'+params.qstring.app_id).insert(newCampaign, function(err, app) {
            let appKey = common.shaHash(app[0]._id, true);
            let d = new Date();
            let timeStamp = d.toISOString();
            let updatedAt = common.getCurrentEpochTime();

            common.db.collection('campaigns'+params.qstring.app_id).update(
                {'_id': app[0]._id}, {$set: {key: appKey,createdat:d,isdeleted:false,status:true, updatedAt:updatedAt}}, function(err, app) {}
            );       

            newCampaign._id = app[0]._id;
            newCampaign.key = appKey;

            //get all the deviceids under this app and inform them of the update, by push
            //get the apikey 
            common.db.collection('apps').findOne({"_id":common.db.ObjectID(params.qstring.app_id)},function(err,result)
            {

                if(!err)    
                {   

                    let isappmodeproduction = false;

                    if(result.isappmodeproduction)
                    {
                        isappmodeproduction = true;
                    }
                    else
                    {
                        isappmodeproduction = false;
                    }
                    
                    if(isappmodeproduction)
                    {
                        apikey = result.gcm_key; 
                    }
                    else
                    {
                        apikey = result.dev_gcm_key;    
                    }

                    let j = 0;     
                    let deviceArr = [];           
                    common.db.collection('app_users'+params.qstring.app_id).find({"p":"Android","gcmid":{'$exists':true}}).toArray(function (err, deviceids) {
                            for (let i = 0; i < deviceids.length ;i++) {
                               if(j == 100 || (i+1 == deviceids.length))
                               {
                                deviceArr.push(deviceids[i]._id);
                                pushApi.sendBulkPushAndroid(apikey,deviceArr,newCampaign);
                                j=0;
                                deviceArr = [];
                               }
                               else
                               {
                                deviceArr.push(deviceids[i]._id);
                                j++;
                               } 
                           }

                           let updatedAt = common.getCurrentEpochTime();
                            //update the total number of devices reached
                            common.db.collection('campaigns'+params.qstring.app_id).update(
                                {'_id': app[0]._id}, {$inc: {totalDevices: deviceids.length}, $set:{updatedAt:updatedAt}}, function(err, app) {}
                        ); 
                    }); 


                    //for ios Push of Direct Campaigns
                    if(result)
                    {   
                        let certPath = ''; 
                        let keyPath = '';
                        let pphrase = '';

                        if(isappmodeproduction)
                        {
                            if(result.hasOwnProperty('ios_cert1'))
                            {
                                //get the ios keys
                                certPath = result.ios_cert1;
                                keyPath = result.ios_cert2;                            
                                pphrase = result.ios_pass1;
                            }
                        }  
                        else
                        {
                           if(result.hasOwnProperty('dev_ios_cert1'))
                            {
                                //get the ios keys
                                certPath = result.dev_ios_cert1;
                                keyPath = result.dev_ios_cert2;                            
                                pphrase = result.dev_ios_pass1;
                            } 
                        }                   
                        
                            let j = 0;
                            let deviceArr = [];           
                            common.db.collection('app_users'+params.qstring.app_id).find({"p":"iOS","gcmid":{'$exists':true}}).toArray(function (err, deviceids) {
                                    for (let i = 0; i < deviceids.length ;i++) {
                                       if(j == 100 || (i+1 == deviceids.length))
                                       {
                                        deviceArr.push(deviceids[i]._id);
                                        pushApi.sendBulkPushApple(params.qstring.app_id,certPath,keyPath,pphrase,deviceArr,newCampaign,isappmodeproduction);
                                        j=0;
                                        deviceArr = [];
                                       }
                                       else
                                       {
                                        deviceArr.push(deviceids[i]._id);
                                        j++;
                                       } 
                                   }

                                    let updatedAt = common.getCurrentEpochTime();
                                    //update the total number of devices reached
                                    common.db.collection('campaigns'+params.qstring.app_id).update(
                                        {'_id': app[0]._id}, {$inc: {totalDevices: deviceids.length}, $set:{updatedAt:updatedAt}}, function(err, app) {}
                                ); 
                            }); 
                    }
                }
            });

            common.returnOutput(params, newCampaign);
        });
    };

    campaignsApi.updateCampaign = function (params) {
        let argProps = {
                '_id': { 'required': true, 'type': 'String' },               
                'name':     { 'required': true, 'type': 'String' },               
                'content': { 'required': false, 'type': 'JSON' },
                'expires': { 'required': false, 'type': 'String' }
            },
            updatedCampaign = {};

        if (!(updatedCampaign = common.validateArgs(params.qstring.args, argProps))) {
            common.returnMessage(params, 400, 'Not enough args mate');
            return false;
        }        

        if (Object.keys(updatedCampaign).length === 0) {
            common.returnMessage(params, 200, 'Nothing changed');
            return true;
        }
    
        let d = new Date();
        let timeStamp = d.toISOString();
        updatedCampaign.updatedAt = timeStamp;
        
        let campid = updatedCampaign._id;
        delete updatedCampaign._id;  

        //updatedCampaign['updatedAt'] = common.getCurrentEpochTime();    
        common.db.collection('campaigns'+params.qstring.app_id).update({'_id': common.db.ObjectID(campid)}, {$set: updatedCampaign}, function(err, rule) {
               common.returnOutput(params, updatedCampaign);
        });
    return true;   
};


    campaignsApi.deleteCampaign = function (params) {        
        let argProps = {
                'campaignid': { 'required': true, 'type': 'String'}
            },
            campaigninfo = {};        

        if (!(campaigninfo = common.validateArgs(params.qstring.args, argProps))) {
            common.returnMessage(params, 400, 'Not enough args');
            return false;
        }

        common.db.collection('campaigns'+params.qstring.app_id).remove({'_id': common.db.ObjectID(params.qstring.args.campaignid)}, {safe: true}, function(err, result) {
            if (!result) {
                common.returnMessage(params, 500, 'Error deleting the Rule or no campaigns available');
                return false;
            }            
            common.returnMessage(params, 200, 'Success');
            return true;
        });
        return true;
    };


    campaignsApi.runCampaign = function (params) {        
        let argProps = {
                'campaignid': { 'required': true, 'type': 'String'}
            },
            campaigninfo = {};

        if (!(campaigninfo = common.validateArgs(params.qstring.args, argProps))) {
            common.returnMessage(params, 400, 'Not enough args');
            return false;
        }

        //get all the deviceids under this app and inform them of the update, by push
        //get the apikey 
        common.db.collection('apps').findOne({"_id":common.db.ObjectID(params.qstring.app_id)},function(err,result)
        {
                if(!err)    
                {
                    apikey = result.gcm_key;

                    let isappmodeproduction = false;

                    if(result.isappmodeproduction)
                    {
                        isappmodeproduction = true;
                    }
                    else
                    {
                        isappmodeproduction = false;
                    }
                    
                    if(isappmodeproduction)
                    {
                        apikey = result.gcm_key; 
                    }
                    else
                    {
                        apikey = result.dev_gcm_key;    
                    }

                    //get the campaign                    
                    common.db.collection('campaigns'+params.qstring.app_id).findOne({"_id":common.db.ObjectID(params.qstring.args.campaignid)},function(err,result)
                    {
                        newCampaign = result;
                        let j = 0;
                        let deviceArr = [];  
                        common.db.collection('app_users'+params.qstring.app_id).find({"p":"Android","gcmid":{'$exists':true}}).toArray(function (err, deviceids) {
                             for (let i = 0; i < deviceids.length ;i++) {
                               if(j == 100 || (i+1 == deviceids.length))
                               {
                                deviceArr.push(deviceids[i]._id);
                                pushApi.sendBulkPushAndroid(params.qstring.app_id,apikey,deviceArr,newCampaign);
                                j=0;
                                deviceArr = [];
                               }
                               else
                               {
                                deviceArr.push(deviceids[i]._id);
                                j++;
                               } 
                           }              
                        });  


                    //for ios Push of Direct Campaigns
                    if(result)
                    {                           
                        if(result.hasOwnProperty('ios_cert1'))
                        {
                            
                            //get the ios keys
                            certPath = result.ios_cert1;
                            keyPath = result.ios_cert2;                            
                            pphrase = result.ios_pass1;
                            let j = 0;
                              let deviceArr = [];           
                            common.db.collection('app_users'+params.qstring.app_id).find({"p":"iOS","gcmid":{'$exists':true}}).toArray(function (err, deviceids) {
                                    for (let i = 0; i < deviceids.length ;i++) {
                                       if(j == 100 || (i+1 == deviceids.length))
                                       {
                                        deviceArr.push(deviceids[i]._id);
                                        pushApi.sendBulkPushApple(params.qstring.app_id,certPath,keyPath,pphrase,deviceArr,newCampaign,isappmodeproduction);
                                        j=0;
                                        deviceArr = [];
                                       }
                                       else
                                       {
                                        deviceArr.push(deviceids[i]._id);
                                        j++;
                                       } 
                                   }

                                    let updatedAt = common.getCurrentEpochTime();
                                    //update the total number of devices reached
                                    common.db.collection('campaigns'+params.qstring.app_id).update(
                                        {'_id': app[0]._id}, {$inc: {totalDevices: deviceids.length}, $set:{updatedAt:updatedAt}}, function(err, app) {}
                                ); 
                            }); 
                        }
                    }
                    });                    
               }

                common.returnMessage(params, 200, 'Campaign Ran Successfully');
            });
        return true;
    };

    function packcampaigns(campaigns) {
        let campaignsObj = [];

        for (let i = 0; i < campaigns.length ;i++) {
            campaignsObj[i] = {
                '_id': campaigns[i]._id,               
                'name': campaigns[i].name,
                'content' : campaigns[i].content,                                             
                'expires' : campaigns[i].expires,               
                'createdat': campaigns[i].createdat,
                'status':campaigns[i].status
            };
        }

        return campaignsObj;
    }

}(campaignsApi));

module.exports = campaignsApi;
