
var Service        = require('./service.js');
var console        = require('gifer-console');

var UniversalParser  = require('./web_client_connect.js').UniversalParser;

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

    console.log("Receive POST data -=START=-", console.logLevel.DEBUG);

    req.on("data", function(postDataChunk) {
        postData += postDataChunk;

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

            // req.removeAllListeners();
            res.end('');
        }
    });

    req.on("end", function() {
        console.log(' POST data length: ' + postData.length, console.logLevel.DEBUG);
        console.log(' POST data: ' + postData, console.logLevel.DEBUG); // + "\nCRC: " + Service.CRC32(postData)

        CommandParser.apply(req, [postData,  function(_outData){
            console.info("Send to client DATA: " + _outData, console.logLevel.DEBUG);

            if (_outData) {
                res.setHeader("Content-Type", "text/text");
                res.end(_outData);
            }
        }]);
    });
}

function CommandParser(_dataIn, onFinish){
    var reqData = Service.Get_CMD(_dataIn);

    UniversalParser.apply(this, [reqData.CMD, reqData.DATA, onFinish]);
}

exports.Parse = Receive_POST_Data;