const sql = require('mssql')
const settings = require("../settings")
// async/await style:
const pool = new sql.ConnectionPool(settings.dbConfig);
const poolConn = pool.connect();
const Log = require("./logMessage");

pool.on('error', err => {
    Log.logStuff('Connect err: ' + err);
    throw err;
})

function getIP(req) {
    var ip = (req.headers["X-Forwarded-For"] ||
        req.headers["x-forwarded-for"] || '').split(',')[0] ||
        req.connection.remoteAddress;
    return ip;
}

function parseCookies(req) {
    var list = {}, rc = req.headers.cookie;
    rc && rc.split(';').forEach(function (cookie) {
        var parts = cookie.split('=');
        list[parts.shift().trim()] = decodeURI(parts.join('='))
    });
    return list;
}

exports.systemAccess = function (req, res) {
    var data = "";
    req.on('data', function (chunk) {
        data += chunk;
    });
    req.on('end', function () {
        poolConn.then((pc) => {
            pc.request()
                .input('ipaddr', sql.VarChar(50), getIP(req))
                .input('rqst', sql.VarChar(sql.MAX), data)
                .output('resp', sql.VarChar(sql.MAX))
                .output('auth', sql.VarChar(50))
                .execute('spLogin', (err, result) => {
                    if (err) {
                        res.writeHead(503, { "Content-Type": "plain/text" });
                        res.write(err);
                        res.end();
                    } else {
                        res.writeHead(200, {
                            "Set-Cookie": "sessid=" + result.output.auth,
                            "Content-Type": "application/json"
                        });
                        res.write(result.output.resp);
                        res.end();
                    }
                })
        })
    })
}

exports.systemService = function (req, res) {
    var data = "";
    req.on('data', function (chunk) {
        data += chunk;
    });
    var cookies = parseCookies(req);
    req.on('end', function () {
        poolConn.then((pc) => {
            pc.request()
                .input('auth', sql.VarChar(50), cookies.sessid)
                .input('rqst', sql.VarChar(sql.MAX), data)
                .output('resp', sql.VarChar(sql.MAX))
                .execute('spSysRoute', (err, result) => {
                    if (err) {
                        res.writeHead(503, { "Content-Type": "plain/text" });
                        res.write(err);
                        res.end();
                    } else {
                        res.writeHead(200, { "Content-Type": "application/json" });
                        res.write(result.output.resp);
                        res.end();
                    }
                })
        })
    })
}

exports.nextPlayer = (game, data, callback) => {
    let obj = JSON.stringify(data); 
    poolConn.then((pc) => {
        pc.request()
            .input('game', sql.Char(5), game)
            .input('rqst', sql.VarChar(sql.MAX), obj)
            .output('resp', sql.VarChar(sql.MAX))
            .execute('spPlayerNext', (err, result) => {
                if (err) {
                    callback(err)
                } else {
                    callback(null, result.output.resp)
                }
            })
    })
}

exports.systemAction = function (token, game, data, callback) {
    let obj = JSON.stringify(data);
    poolConn.then((pc) => {
        pc.request()
            .input('tokn', sql.VarChar(50), token)
            .input('game', sql.Char(5), game)
            .input('rqst', sql.VarChar(sql.MAX), obj)
            .output('resp', sql.VarChar(sql.MAX))
            .execute('spSysAction', (err, result) => {
                if (err) {
                    callback(err)
                } else {
                    callback(null, result.output.resp)
                }
            })
    })
}

exports.systemExit = () => {
    console.log('good bye')
}