var postback_url = {},
    request= require('request'),
    moment = require('moment'),
    common = require('./../utils/common.js'),
    semusiConfig = require('./../config.js'),
    winstonLogger = require('./../utils/winston'),
    cacheApi = require('./../utils/semusi.cache.js');

(function(postback_url){
  	postback_url.sendInstall = function(postBackUrl, dataObj){
          postBackUrl.uid = postBackUrl.clickid;
          delete postBackUrl.clickid;
  		// Send push using the "request" package
          request({
              uri: postBackUrl,
              method: 'POST',
              headers:{
                  'Content-Type':'application/json'
              },
              json: dataObj
          }, function (err, res, body) {
              // Request error?
              if (err) {
                   
              }
              // body error?
              if (body.error) {
                   
              }

              // Check for 200 OK
              if (res.statusCode != 200) {
                   
              }
              else if (res.statusCode == 200){
              	 
              }
          });
  	}

    postback_url.sendEvents = function(app_id, data){
        if(data.ref){
            cacheApi.getKey("app_id"+app_id+data.ref,function(err,result){
                if(result && result != null){
                    var sendUrl = result;
                    // add question mark into url if does not exists
                    if(sendUrl.indexOf('?') == -1){
                        sendUrl = sendUrl +'?';
                    }

                    if(data.ref == 'rationalheads' || data.ref == 'rational_heads'){
                        sendUrl += 'click_id='+data.clickid+"&event="+data.eventname+"&etime="+data.etimes.etime+"&segment="+JSON.stringify(data.segment);
                    }
                    else{
                        sendUrl += 'ad_network_transaction_id='+data.clickid+"&eventname="+data.eventname+"&etime="+data.etimes.etime;
                    }
                    var postBackUrl = sendUrl+"&ptime="+data.etimes.ptime+"&did="+data.did;

                    // Send push using the "request" package
                    request({
                        uri: sendUrl,
                        method: 'POST'
                        //json: dataObj
                    }, function (err, res, body) {
                        // Request error?
                        if (err) {
                             
                            postback_url.createCallBackLog(app_id, 'sendEvents', {postBackUrl:postBackUrl, err:err, statusCode:res.statusCode});
                        }
                        // body error?
                        if (body.error) {
                             
                            postback_url.createCallBackLog(app_id, 'sendEvents', {postBackUrl:postBackUrl, berr:body.error, statusCode:res.statusCode});
                        }

                        // Check for 200 OK
                        if (res.statusCode != 200) {
                             
                            postback_url.createCallBackLog(app_id, 'sendEvents', {postBackUrl:postBackUrl, statusCode:res.statusCode});
                        }
                        else if (res.statusCode == 200){
                             
                            postback_url.createCallBackLog(app_id, 'sendEvents', {postBackUrl:postBackUrl, body:body, statusCode:res.statusCode});
                        }
                    });
                }
            });
        }
        else{
            postback_url.createCallBackLog(app_id, 'sendEvents', {data:data, err:'refname not found'});
        }
    }

    // prepare webhookdata
    postback_url.prepareWebHookData = function(app_id, data, type, callback){
        var key = "webhook_" + type + "_"+app_id;
        if(type == 'uninstall'){
            key = "webhook_installs_"+app_id;
        }

        cacheApi.getKey(key, function(err,result){

            if(result && result != null){

                result = JSON.parse(result);
                if(result.url){
                    // define variable of json data
                    var jsonData = {};

                    // Attribute setup for events
                    if(type == 'events'){
                        jsonData['device_id'] = data.device_id;
                        jsonData['timestamp'] = data.timestamp;
                        jsonData['app_name'] = data.app_name;
                        jsonData['event'] = [];
                        if(data.events){
                            data.events.forEach(function(event){
                                var obj = {};
                                obj.key = event.key;
                                obj.sid = event.sid;
                                if(event.eventTime){
                                    obj.click_dateTime = moment(event.eventTime*1000).format('DD-MM-YYYY HH:mm:ss');
                                }
                                if(event.segment){
                                    obj.segment = event.segment;
                                }

                                if(event.context.who && event.context.who.device){
                                    obj.device = {model:event.context.who.device.d, platform:event.context.who.device.pv, app_version:event.context.who.device.av, carrier:event.context.who.device.c}
                                }

                                if(event.context.where){
                                    var ip = '';
                                    if(event.context.where.ip){
                                        ip = event.context.where.ip;
                                    }

                                    if(event.context.where.geo && event.context.where.geo.cty && event.context.where.geo.cc){
                                       obj.geo = {city:event.context.where.geo.cty, country:event.context.where.geo.cc, ip:ip}
                                   }
                                }
                                if(event.key != '_App_Stop'
                                    && event.key != '_App_Start'
                                    && event.key != 'Session_Start'
                                    && event.key != 'Session_End'
                                    && event.key != 'CSession_Start'
                                    && event.key != 'CSession_End'
                                    && event.key != 'App_Foreground'
                                    && event.key != 'App_Background'
                                    && event.key != 'Campaign_Received'
                                    && event.key != 'Campaign_Viewed'
                                    && event.key != 'Campaign_Clicked'
                                    && event.key != 'Campaign_Deleted'
                                    && event.key != 'install'
                                    && event.key != 'uninstall'){

                                    jsonData['event'].push(obj);
                                }

                            });

                        }

                        // validate event array
                        if(jsonData.event && jsonData.event.length <= 0){
                             
                            callback(null, null);
                            return false;
                        }
                    }
                    else{
                        jsonData = data;
                    }

                    jsonData['method'] = result.method;
                    jsonData['dType'] = type;
                     
                     
                    callback(result.url, jsonData);
                }
                else{
                     
                    callback(null, null);
                }
            }
            else{
                 
                callback(null, null);
            }
        });
    }

	  // send information
    postback_url.webHook = function(app_id, url, jsonData){
        // Send push using the "request" package
        if(url.indexOf('?') == -1){
            url = url +'?';
        }
         
         
        // take method type of request
        var method = jsonData.method;
        delete jsonData.method;

        if(method == 'GET'){
            url += common.jsonToqstring(jsonData);
        }

        if(jsonData.dType){
            request({
                uri: url,
                method: method,
                json: jsonData
            }, function (err, res, body) {
                // Request error?
                if (err) {
                     
                    jsonData.err = err;
                    postback_url.createCallBackLog(app_id, 'webhook_error', jsonData);
                }
                // body error?
                /*if (body.error) {
                     
                    jsonData.berr = body.error;
                    postback_url.createCallBackLog(app_id, 'webhook', jsonData);
                }*/
                jsonData.url = url;
                // Check for 200 OK
                if (res.statusCode && res.statusCode != 200) {
                     
                    jsonData.res = res;
                    postback_url.createCallBackLog(app_id, 'webhook', jsonData);
                }
                else if (res.statusCode && res.statusCode == 200){
                     
                    jsonData.res = res;
                    postback_url.createCallBackLog(app_id, 'webhook', jsonData);
                }
                else if (res.statusCode == undefined) {
                    jsonData.res = res;
                    postback_url.createCallBackLog(app_id, 'webhook_error', jsonData);
                }
            });
        }
    }

    postback_url.createCallBackLog = function(app_id, name, data){
        // var logDir = semusiConfig.callbackLog;
        // var fileName = logDir + "/postback_"+ app_id + "_" + moment().year()+''+(moment().month()+1)+''+moment().date()+".log";
        // var log = fs.createWriteStream(fileName, {'flags': 'a'});
        // use {'flags': 'a'} to append and {'flags': 'w'} to erase and write a new file
        //log.end(JSON.stringify(data,null,4)+",");
        winstonLogger.init('postback_'+name+"_"+app_id, true);
		    winstonLogger.writeData(data);
    }

    postback_url.createLog = function(app_id, queryString, filename){
        // var logDir = semusiConfig.callbackLog;
        // var fileName = logDir + "/"+filname+ app_id + "_" + moment().year()+''+(moment().month()+1)+''+moment().date()+".log";
        // var log = fs.createWriteStream(fileName, {'flags': 'a'});
        // use {'flags': 'a'} to append and {'flags': 'w'} to erase and write a new file
        //log.end(JSON.stringify(queryString,null,4)+",");
        winstonLogger.init(filename+ app_id, true);
		    winstonLogger.writeData(queryString);
    }

}(postback_url));

module.exports = postback_url;
