let rulesApi = {},
    common = require('./../../utils/common.js'),
    logger = require('../../../logger'),
    fs = require('fs');
    GCM = require("gcm").GCM; 

(function (rulesApi) {

    rulesApi.getAllRules = function (params) {

        common.db.collection('rules'+params.qstring.args.app_id).find({}).toArray(function (err, rules) {
            let rulesObj = packRules(rules);
            common.returnOutput(params, rulesObj);
            return true;
        });
        return true;
    };


    rulesApi.createRule = function (params) {
         let argProps = {
                'name':     { 'required': true, 'type': 'String' },
                'when':  { 'required': false, 'type': 'JSON' },
                'where': { 'required': false, 'type': 'JSON' },
                'who': { 'required': false, 'type': 'JSON' },
                'what': { 'required': false, 'type': 'JSON' },
                'pushfrequencyperinstance': { 'required': false, 'type': 'String' },
                'pushfrequencyperhr': { 'required': false, 'type': 'String' },
                'content': { 'required': false, 'type': 'JSON' },              
                'expires': { 'required': false, 'type': 'String' },
                'starting': { 'required': false, 'type': 'String' },
                'since' : { 'required': false, 'type': 'String' },
                'interests' : { 'required': false, 'type': 'String' }
            },
            newRule = {};

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

        //add the createdAt and updatedAt fields        
        common.db.collection('rules'+params.qstring.args.app_id).insert(newRule, function(err, app) {
            let appKey = common.shaHash(app[0]._id, true);
            let timeStamp = Date.now();

            common.db.collection('rules'+params.qstring.args.app_id).update(
                {'_id': app[0]._id}, {$set: {key: appKey,createdAt:timeStamp,updatedAt:timeStamp}}, function(err, app) {}
            );       

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

            //get all the deviceids under this app and inform them of the update, by push
            //using query like db.app_users531f041fc826a7f310000001.find({},{"did":true})
            //Update do not send push at the create of campaign
            common.db.collection('app_users'+params.qstring.args.app_id).find({},{"gcmid":true}).toArray(function (err, deviceids) {
                for (let i = 0; i < deviceids.length ;i++) {
                   let deviceid = deviceids[i].gcmid;
                   //sendPush(deviceid,"#getallrules");                     
                }

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

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

    rulesApi.updateRule = function (params) {
        let argProps = {
                'name':     { 'required': true, 'type': 'String' },
                'when':  { 'required': false, 'type': 'JSON' },
                'where': { 'required': false, 'type': 'JSON' },
                'what': { 'required': false, 'type': 'JSON' },
                'who': { 'required': false, 'type': 'JSON' },
                'content': { 'required': false, 'type': 'JSON' },
                'pushfrequencyperinstance': { 'required': false, 'type': 'String' },
                'pushfrequencyperhr': { 'required': false, 'type': 'String' },                
                'expires': { 'required': false, 'type': 'String' },
                'starting': { 'required': false, 'type': 'String' },
                'since' : { 'required': false, 'type': 'String' },
                'interests' : { 'required': false, 'type': 'String' }
            },
            updatedRule = {};

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

        if (Object.keys(updatedRule).length === 0) {
            common.returnMessage(params, 200, 'Nothing changed');
            return true;
        }
    
        updatedRule.updatedAt = Date.now();

        common.db.collection('rules'+params.qstring.args.app_id).update({'name': params.qstring.args.name}, {$set: updatedRule}, function(err, rule) {
               common.returnOutput(params, updatedRule);
                
                //get all the deviceids under this app and inform them of the update, by push
                //using query like db.app_users531f041fc826a7f310000001.find({},{"did":true})
                common.db.collection('app_users'+params.qstring.args.app_id).find({},{"gcmid":true}).toArray(function (err, deviceids) {
                    for (let i = 0; i < deviceids.length ;i++) {
                       let deviceid = deviceids[i].gcmid;
                       sendPush(deviceid,"#getallrules#update#"+params.qstring.args.campaign_id);                     
                    }
                   //update the total number of devices reached
                   logger.info(`campaign id is==>> ${params.qstring.args.campaign_id} :::: and total devices ${deviceids.length}`);
                    common.db.collection('rules'+params.qstring.args.app_id).update(
                        {'_id': common.db.ObjectID(params.qstring.args.campaign_id)}, {$set: {'totalDevices': deviceids.length, 'updatedAt':updatedRule.updatedAt}}, function(err, app) {}); 
                //});*/   

            });
     
        return true;
    });
};

    rulesApi.deleteRule = function (params) {        
        let argProps = {
                'app_id': { 'required': true, 'type': 'String', 'min-length': 24, 'max-length': 24 },
                'name': { 'required': true, 'type': 'String'}
            },
            appId = '';

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

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

            //get all the deviceids under this app and inform them of the update, by push
            //using query like db.app_users531f041fc826a7f310000001.find({},{"did":true})
            common.db.collection('app_users'+params.qstring.args.app_id).find({},{"gcmid":true}).toArray(function (err, deviceids) {
                    for (let i = 0; i < deviceids.length ;i++) {
                       let deviceid = deviceids[i].gcmid;
                       sendPush(deviceid,"#getallrules#delete#"+params.qstring.args.campaign_id);                     
                    }
            });   

            return true;
        });
        return true;
    };

    rulesApi.resetRule = function (params) {
        let argProps = {
                'app_id': { 'required': true, 'type': 'String', 'min-length': 24, 'max-length': 24 }
            },
            appId = '';

       common.db.collection('rules'+params.qstring.args.app_id).remove({}, {safe: true}, function(err, result) {
            if (!result) {
                common.returnMessage(params, 500, 'Error deleting the Rules');
                return false;
            }            
            common.returnMessage(params, 200, 'Success');

             //get all the deviceids under this app and inform them of the update, by push
             //using query like db.app_users531f041fc826a7f310000001.find({},{"did":true})
            common.db.collection('app_users'+params.qstring.args.app_id).find({},{"gcmid":true}).toArray(function (err, deviceids) {
                    for (let i = 0; i < deviceids.length ;i++) {
                       let deviceid = deviceids[i].gcmid;
                       sendPush(deviceid,"#getallrules");                     
                    }
            });      

            return true;
        });
        return true;
    };

    //function to send the push about new Rules availabilibity or change in rules to the device
    function sendPush(gcmid,content)
    {

     /*ua = require("urban-airship");
        ua = new ua("AB7xUl6dQkK0RpHUze-8cA", "YN0yQJYEQJSzLyFWSGmWfg", "xX2t3KSGSCClNEC2vZMYvg");    
        //payload1 = {"android":{"alert":"","extra":{"command":"#getallrules"}},"apids":[gcmid]};
    payload1 = {"android":{"alert":"","extra":{"command":content}},"apids":[gcmid]};

        ua.pushNotification("/api/push", payload1, function(error) {
                
               return true;
        });*/

    logger.info(`push being sent content is =>  ${content}`);
    let payload1 = {registration_id:gcmid,'data.message': content};        
    gcm = require('gcm').GCM;
    let apikey = 'AIzaSyBLC7Zsu9MjwYm2VrwZ960-jhOFiiZg5Go';
    let gcm = new GCM(apikey);

    gcm.send(payload1, function(err, messageId){
        if (err) {
            logger.error(`error => ${err}`); 
        } else {
            logger.info(`Sent with message ID:> ${messageId}`); 
        }
    });

        return true;
    }


    function packRules(rules) {
        let rulesObj = {};

        for (let i = 0; i < rules.length ;i++) {
            rulesObj[rules[i]._id] = {
                '_id': rules[i]._id,
                'name' : rules[i].name,
                'when' : rules[i].when,
                'where' : rules[i].where,
                'what': rules[i].what,
                'who' : rules[i].who,
                'content' : rules[i].content,                
                'pushfrequencyperinstance': rules[i].pushfrequencyperinstance,
                'pushfrequencyperhr': rules[i].pushfrequencyperhr,                
                'expires' : rules[i].expires,
                'starting' : rules[i].starting,
                'totalDevices' : rules[i].totalDevices,
                'since' : rules[i].since,
                'interests' : rules[i].interests,
                'createdAt': rules[i].createdAt,
                'updatedAt': rules[i].updatedAt
            };
        }

        return rulesObj;
    }

}(rulesApi));

module.exports = rulesApi;
