var botsSession = {},
    dataProducer = require('../utils/common.data.producer.js'),
    cacheApi = require('../utils/semusi.cache.js'),
    botsUser = require('./bots.user.js'),
    commonBots = require('./common.js'),
    semusiConfig = require('./../config'),
    common = require('../utils/common.js'),
    moment = require('moment');
    
(function (botsSession) {
    botsSession.checkNewSession = function(params, botEvent){
        //Validate user session
        var sid = commonBots.getSenderId(botEvent);
        var timestamp = commonBots.getEventTime(botEvent);
        var cacheKey = "chat_bot"+params.appid+sid;
        cacheApi.getKey(cacheKey,function(err,result){
            if(err || result==null){
                //set app information into cache
                cacheApi.setKey(cacheKey,JSON.stringify({timestamp:timestamp}));                
                // set expaire time
                cacheApi.expire(cacheKey,semusiConfig.chatbot_session_time);
                // call new session
                botsSession.newSession(params, botEvent);
            }
            else{
                result = JSON.parse(result);
                var duration = parseInt(parseInt(timestamp)-parseInt(result.timestamp));
                botsSession.endSession(params, sid, duration, timestamp);
                //set app information into cache
                cacheApi.setKey(cacheKey,JSON.stringify({timestamp:timestamp}));
                // update expairy time
                cacheApi.expire(cacheKey,semusiConfig.chatbot_session_time);               
            }
        });     
    }

    botsSession.newSession = function(params, botEvent){
        var sid = commonBots.getSenderId(botEvent);
        var timestamp = commonBots.getEventTime(botEvent);

        if(params.platform && timestamp && sid){
            var timelySession  = {}, time =common.getDayTime(timestamp);
            var platform = params.platform.toLowerCase();
            common.fillTimeObjectWithEpoch(platform, timestamp, timelySession, time+".total");
            common.fillTimeObjectWithEpoch(platform, timestamp, timelySession, "total");

            var mKey = params.appid+moment.unix(timestamp).format('YYYYM');
            cacheApi.addToSadd(mKey, sid, function(data){
                if(data){
                    var mauKey = common.getDauMauKey(platform, timestamp, 'mau');
                    timelySession[mauKey] = 1;
                    cacheApi.expire(mKey,60*60*24*30); // set expaire key time in seconds for one day
                    
                    // check user exists or not
                    botsUser.checkUser(params, botEvent, function(res){
                        if(!res){
                            botsUser.newInstalls(params, botEvent); // install new user if not exists
                            timelySession[platform+'_active_users'] = 1;
                        }
                        else{
                            // update new session information
                            botsUser.processBegginSession(params, botEvent);
                        }
                        // manage DAU key into redis server
                        var key = params.appid+moment.unix(timestamp).format('YYYYMD');
                        cacheApi.addToSadd(key, sid, function(data){
                            if(data){
                                var dauKey = common.getDauMauKey(platform, timestamp, 'dau');
                                timelySession[dauKey] = 1;
                                cacheApi.expire(key,60*60*24); // set expaire key time in seconds for one day
                            }

                            // add into optimize collection
                            common.db.collection('timely_chatbot_sessions').update({'_id':common.db.ObjectID(params.appid)},{'$inc': timelySession}, {'upsert':true}, function (err,result) {
                                if(!err){   
                                }
                                else{
                                }    
                            });
                        });
                    }); 
                }    
                else{
                    // manage DAU key into redis server
                    var key = params.appid+moment.unix(timestamp).format('YYYYMD');
                    cacheApi.addToSadd(key, sid, function(data){
                        if(data){
                            var dauKey = common.getDauMauKey(platform, timestamp, 'dau');
                            timelySession[dauKey] = 1;
                            cacheApi.expire(key,60*60*24); // set expaire key time in seconds for one day
                        }

                        // update new session information
                        botsUser.processBegginSession(params, botEvent);

                        // add into optimize collection
                        common.db.collection('timely_chatbot_sessions').update({'_id':common.db.ObjectID(params.appid)},{'$inc': timelySession}, {'upsert':true}, function (err,result) {
                            if(!err){      
                            }
                            else{
                            }    
                        });
                    });
                }
                
            });   
        }
    }

    botsSession.endSession = function(params, sid, duration, timestamp){
        var platform = params.platform.toLowerCase();
        var timelySession = {}, time =common.getDayTime(timestamp);
        // update end session into app user collection
        botsUser.processEndSession(params.appid, sid, duration, timestamp);

        // prepare aggregate collection for store session duration
        timelySession[platform+"."+moment(timestamp*1000).format("YYYY.M.D")+'.'+time+'.tsd'] = duration;
        timelySession[platform+"."+moment(timestamp*1000).format("YYYY.M.D")+'.tsd'] = duration;
        timelySession[platform+"."+moment(timestamp*1000).format("YYYY.M")+'.tsd'] = duration;
        timelySession[platform+"."+moment(timestamp*1000).format("YYYY")+'.tsd'] = duration;
        timelySession[platform+".tsd"] = duration;
        // add duration into optimize collection
        common.db.collection('timely_chatbot_sessions').update({'_id':common.db.ObjectID(params.appid)},{'$inc': timelySession}, {'upsert':true}, function (err,result) {
            if(!err){      
            }
            else{
            }    
        });
    }

    //botsSession.checkSessionInterval();
    botsSession.processToSession = function(params, botEvent){
        var sid = commonBots.getSenderId(botEvent);
        var timestamp = commonBots.getEventTime(botEvent);
        var obj = {
                    appid       : params.qstring.appid,
                    user_id     : common.crypto.createHash(semusiConfig.shaV1Hash).update(sid+"").digest('hex'),
                    timestamp   : timestamp,
                    event       : botEvent,
                    params      : params.qstring,
                    key         : semusiConfig.ChatBotKey
                };
        // process data into sqs
        dataProducer.writeDataDirectly(obj);
    }                                                                       

}(botsSession));

module.exports = botsSession;
