/**
 * Created by Gifer on 06.04.2016.
 */

 "use strict";

 var Service = require('../service.js');
 var URL     = require('url');
 var console = require('gifer-console');
 var qString = require('querystring');
 var CMD     = require('../cmd/cmd').CMD;

 function sendApiCmdToServer(req, res) {
     var postData   = '';

     function send(postData, res, ip) {
         if (Service.isObject(postData)){
             postData.hash = Service.RandomHash(15);

             console.log("sendApiCmdToServer. " + JSON.stringify(postData), console.logLevel.DEBUG);

             require('./mcInternalConnection').sendDataFromInternalServer(
                 CMD.ns_integrationAPI + '=' + ip + '=' + postData.cmd + JSON.stringify(postData),

                 function(info){
                     try {
                         delete info.hash;
                         delete info.CMD;
                     }catch (e) {}

                     var out = JSON.stringify(info);

                     console.log("CMD.ns_integrationAPI. " + out, console.logLevel.DEBUG);

                     res.end(Service.convertToEntities(out));
                 },
                 postData.hash
             );
         } else {
             res.end("Access denied. Can't convert data to object");
         }
     }

     if (req.method === "POST"){
         var dataLength = req.headers['content-length'];
         var apiVer     = req.headers.hasOwnProperty('integrationapi') ? req.headers['integrationapi'] : null;

         if (apiVer || dataLength < MCServer.maxUploadData){
             req.addListener("data", function(postDataChunk) {
                 postData += postDataChunk;

                 if (postData.length > MCServer.maxUploadData){
                     console.err("Too long POST data. Break connection.", console.logLevel.ERROR);

                     req.removeAllListeners();
                     res.end('POST content too large. Access denied.');
                 }
             });

             req.addListener("end", function() {
                 postData = Service.StringToObj(postData);

                 send(postData, res, req.remoteHostIp || "127.0.0.1");
             });
         } else {
             res.end('Access denied. Unknown API version or data length too large');
         }
     } else
         
     if (req.method === "GET") {
         var query = null;

         try{
             query = qString.parse(URL.parse(req.url).query);
         } catch (e){
             res.end('Access denied. Not find query string');

             return;
         }

         postData = Service.StringToObj(query.data);

         send(postData, res, req.remoteHostIp || "127.0.0.1");
     } else {
         res.end('Access denied. Unknown method');
     }
 }

 exports.sendApiCmdToServer = sendApiCmdToServer;



