/**
 * Created by Gifer on 24.05.2017.
 */

"use strict";

const Service    = require('../service');
const console    = require('gifer-console');
const URL        = require('url');
const CMD        = require('../cmd/cmd').CMD;
const CRLF       = "\r\n";
const logLevel   = console.logLevel.DEBUG;
const crypto     = require('crypto');

module.exports = function API(req, res) {
    var sendDataInternal = require('./mcInternalConnection').sendDataFromInternalServer;
    var hash   = "";
    var url    = "";
    var params = "";
    var script = "";
    var query  = {};

    function result (data) {
        console.log('REST: send data from server to telegram bot!', logLevel);

        delete data.hash;
        delete data.CMD;

        if (data.Error) {
/*
            var msg = "";

            switch (data.Error) {
                case CMD.nsInternalErrors.TELEGRAM_SCRIPT_NOT_FOUND     :
                    msg = "Telegram script not found";
                break;

                case CMD.nsInternalErrors.TELEGRAM_SCRIPT_DISABLED      :
                    msg = "Telegram script disabled";
                break;

                case CMD.nsInternalErrors.INVALID_SCRIPT_RESULT         :
                    msg = "Invalid script result";
                break;

                case CMD.nsInternalErrors.SCRIPT_TIMED_OUT              :
                    msg = "Script timed out";
                break;

                case CMD.nsInternalErrors.SCRIPT_SYNTAX                 :
                    msg = "Script syntax error";
                break;

                case CMD.nsInternalErrors.SCRIPT_RUNTIME                :
                    msg = "Script runtime error";
                break;

                case CMD.nsInternalErrors.SCRIPT_NO_ONREQUESTBYREST     :
                    msg = "Script OnRequestByRest not found";
                break;

                case CMD.nsInternalErrors.SCRIPT_INVALID_ONREQUESTBYREST:
                    msg = "Invalid script OnRequestByRest";
                break;
            }

            data.message  = msg;
*/
            data.helpLink = "https://nsoft-s.com/" + (MCServer.Lang === "ru" ? "" : (MCServer.Lang === "uk" ? "ua/" : "en/")) + "mcserverhelp/index.html?scriptseventsonrequestbyresterrorslist.htm";

            res.statusCode = 403;
        }

        res.end(JSON.stringify(data));
    }

    try {
        hash   = Service.RandomHash(10);
        url    = URL.parse(req.url);
        params = url.search;
        script = url.pathname.split('/')[2];

        console.log('REST: request', logLevel);
    } catch (e){
        console.err('REST: ' + e.message, console.logLevel.ERROR);
        console.err('REST: ' + e.stack, console.logLevel.ERROR);
    }

    if (script){
        switch (script){
            case "_lobbyGetServerName_":
                if (MCServer.Lobby){
                    const sha1 = crypto.createHash('sha1');

                    res.end(JSON.stringify({
                        MCPort          : MCServer.MCPort,
                        ServerName      : MCServer.ServerName,
                        UseServerPass   : MCServer.UseServerPass,
                        // OnlySecuredLogin: MCServer.OnlySecuredLogin,
                        ServPass        : sha1.update(MCServer.ServPass).digest('hex'),
                        ServerID        : MCServer.ServerID,
                        Aliases         : MCServer.Aliases
                    }));
                } else {
                    res.statusCode = 403;
                    res.end(Service.Const.denied);
                }
            break;

            case "_androidQrCode_":
                if (MCServer.Lobby){
                    let postData = '';

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

                        if (postData.length > MCServer.maxUploadData){
                            console.err('REST: too big POST data. Break connection.', console.logLevel.ERROR);

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

                    req.addListener("end", function() {
                        let out = {
                            "Addr"      : postData,
                            "Port"      : MCServer.MCPort,    // optional, default 2004
                            "NodePort"  : MCServer.Port,
                            "SSL"       : MCServer.WEBUseSSL,
                            "ServerPwd" : MCServer.ServPass
                        };

                        if (MCServer.ExternalIP && MCServer.ExternalIP !== postData) {
                            out.AddrAlt = MCServer.ExternalIP;
                            out.PortAlt = MCServer.MCPort;
                        }
                        
                        res.end(Service.EncryptBase64("3d9LKIJF$EGyncoi@uw5#ty9phsdfbrw560p", JSON.stringify(out)));
                    });
                } else {
                    res.statusCode = 403;
                    res.end(Service.Const.denied);
                }
            break;

            default:
                query = {
                    hash   : hash,
                    params : params,
                    script : script,
                    url    : url.pathname,
                    ip     : req.remoteHostIp,
                    type   : req.method,
                    headers: req.rawHeaders && Service.isArray(req.rawHeaders) ? req.rawHeaders.join(CRLF) : "",
                    body   : ""
                };

                console.log('REST: ' + req.method, logLevel);

                if (req.method === "GET"){
                    query.body = params || "";

                    console.log('REST: ' + JSON.stringify(query), logLevel);

                    sendDataInternal(CMD.ns_rest_request + '=' + JSON.stringify(query), result, hash);
                } else

                if (req.method === "POST") {
                    let postData = '';

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

                        if (postData.length > MCServer.maxUploadData){
                            console.err('REST: too big POST data. Break connection.', console.logLevel.ERROR);

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

                    req.addListener("end", function() {
                        console.log('REST: ' + JSON.stringify(query), logLevel);

                        query.body = postData;

                        sendDataInternal(CMD.ns_rest_request + '=' + JSON.stringify(query), result, hash);
                    });
                }
        }
    } else {
        res.end('REST: Unknown script or bot token:\n' + script);
    }
};