var Azure = require('azure-storage'),
    logger = require('../../../logger'),
    appICEConfig = require('../../config/config'),
    poller = require('../core/poller'),
    common = require('../common/common'),
    dataConsumer = require('../core/dataprocessor'),
    usage = require('../core/installprocessor'),
    async = require('async');
    semusiConfig = require('../../config');
var storeQueue = Azure.createQueueServiceWithSas(appICEConfig.azureStorageCreds.sasUrl, appICEConfig.azureStorageCreds.sasToken);

poller.onPoll(() => {
     
    // receive message from azure queue
    storeQueue.getMessages(appICEConfig.azureQueue.installQueue, {
        numOfMessages: appICEConfig.azureStorageCreds.numMessage,
        visibilityTimeout: appICEConfig.azureStorageCreds.visibilityTimeout
    }, function(error, results, getResponse) {
        if (error || results.length == 0) {
            //poller.poll(); // Wait for the next message
            processEvents();
        } else {
            try {
                async.each(results, function(message, callback) {
                    var dataObject = JSON.parse(message.messageText);
                    logger.info(`Data Object =>: ${dataObject}`);
                    dataObject.SQS = true;
                    dataObject.skipPreviousDateCheck = true;
                    dataObject.app_user_id = common.crypto.createHash(semusiConfig.shaV1Hash).update(dataObject.app_key + dataObject.device_id + "").digest('hex');
                    let params = {
                        qstring: dataObject,
                        ip_address: dataObject.ip_address,
                        user: {
                            cc: "",
                            country: "",
                            city: "",
                            lat: "",
                            lng: ""
                        },
                        app_user_id: dataObject.app_user_id,
                        did: dataObject.device_id,
                        time: dataObject.timestamp
                    }
                    usage.initialize(params, function(res) {
                        logger.info(`params =>: ${params}`);
                        // delete message from queue
                        storeQueue.deleteMessage(appICEConfig.azureQueue.installQueue, message.messageId, message.popReceipt, function(error, deleteResponse) {
                            if (!error) {
                                 
                            }
                            callback();
                        });
                    });
                }, function(e, res) {
                     
                    poller.poll(); // Wait for the next message
                });
            } catch (e) {
                logger.error(`error is => ${e}`);
                //done();
                poller.poll(); // Wait for the next message
            }
        }
    });
});


//Process events Data
function processEvents() {
    storeQueue.getMessages(appICEConfig.azureQueue.eventsQueue, {
        numOfMessages: 30,
        visibilityTimeout: 5 * 60
    }, function(error, results, getResponse) {
        if (error || results.length == 0) {
            poller.poll(); // Wait for the next message
        } else {
            async.each(results, function(message, callback) {
                dataObject = JSON.parse(message.messageText);   
                var obj = {
                              appid : dataObject.app_id,
                              did: dataObject.device_id,
                              user_id: dataObject.app_user_id,
                              events: dataObject.events,
                              key : "events"
                          };
                dataObject.key="events";
                logger.info(`Data Object =>: ${dataObject}`);
                var data = [{
                    appid: dataObject.appid,
                    dataArray: [dataObject]
                }];
                logger.info(`Data Object key =>: ${dataObject.key}`);
                switch (dataObject.key) {
                    case "beginsession": {
                        dataConsumer.processBeginSessionData(data, function(status) {
                            if (status) {

                            }
                        });
                        break;
                    }
                    case "endsession": {
                        dataConsumer.processEndSessionData(data, function(status) {
                            if (status) {

                            }
                        });
                        break;
                    }
                    case "genericQueue": {
                        dataConsumer.processEvents(data, function(status) {
                            if (status) {

                            }
                        });
                        break;
                    }
                    case "events": {
                        dataConsumer.processEvents(data, function(status) {
                            if (status) {

                            }
                        });
                        break;
                    }
                    case "eventsqueue": {
                        dataConsumer.processEvents(data, function(status) {
                            if (status) {

                            }
                        });
                        break;
                    }
                    case "competingApps": {
                        dataConsumer.processCompetingApps(data, function(status) {
                            if (status) {

                            }
                        });
                        break;
                    }
                    case "genericQueue_competingApps": {
                        dataConsumer.processCompetingApps(data, function(status) {
                            if (status) {

                            }
                        });
                        break;
                    }
                    case "bulkResponse": {
                        dataConsumer.processCampaignResponses(data, function(status) {
                            if (status) {

                            }
                        });
                        break;
                    }
                    case "beginchatbotsession": {
                        dataConsumer.processBeginChatBotSessionData(data, function(status) {
                            if (status) {

                            }
                        });
                        break;
                    }
                }

                // delete message from queue
                storeQueue.deleteMessage(semusiConfig.azureApiQueueMap['genericQueue'], message.messageId, message.popReceipt, function(error, deleteResponse) {
                    if (!error) {
                         
                    }
                    callback();
                });
            }, function(e, res) {
                logger.error(`error is => ${e}`);
                poller.poll(); // Wait for the next message
            });
        }
    });
}

poller.poll();