var botsApi = {},
	qs = require('querystring'),
    botsEvents = require('./bots.event.js'),
    common = require('../utils/common.js');

(function (botsApi) {

botsApi.processMessage = function(params) {	
	switch(params.qstring.platform){
		case "facebook":
			processFacebookMessages(params);
			break;
		case "slack":
			processSlackMessages(params);
			break;
		default:
			returnMessage(params,200,{result:"Failed"});		
		break;

	}
}

function processFacebookMessages (params) {
	if (params.req.method == 'POST') {
        processPost(params,function(data){  
        	if(params.qstring.type=="incoming"){
                data.eventKey = params.qstring.type;
                data.platform = params.qstring.platform;
                botsEvents.sendEventData(params, data);
        	}   
        	else if(params.qstring.type=="outgoing"){
                data.time = common.getCurrentEpochTime();
                data.eventKey = params.qstring.type;
                data.platform = params.qstring.platform;
                botsEvents.sendEventData(params, data);
        	}                                                      
 			
 			returnMessage(params,200,{result:"Success"});           
        });
    }
    else{
    	returnMessage(params,200,{result:"Failed"});		
    }
}

function processSlackMessages (params) {
	if (params.req.method == 'POST') {
        processPost(params,function(data){                                                            
 			returnMessage(params,200,{result:"Success"});           
        });
    }
    else{
    	returnMessage(params,200,{result:"Failed"});		
    }
	
}

function returnMessage(params,code,output){
	params.res.writeHead(code, {'Content-Type': 'application/json; charset=utf-8'});
	params.res.write(JSON.stringify(output));        
    params.res.end();
}

function processPost(params, callback,skipDidCheck) {
    var body = "";
    params.req.on('data', function(data) {
        body += data;
    });

    params.req.on('end', function() {            
        var postdata = body;                      
        if(postdata){
            try{
                postdata = JSON.parse(postdata);    
            }
            catch(e){
                returnMessage(params, 200, {result:"JSON data not well formatted"});
            }
            
        }                      
        callback(postdata);
    });
}

}(botsApi));

module.exports = botsApi;