/*
 * Copyright 2021 Netsyms Technologies.
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

const http_port = 36744; // dialed ENSIG on phone keypad (eNotary Signature)
var http = require('http');
var server = http.createServer(function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    if (req.method == "GET") {
        console.log("Serving " + req.url);
        switch (req.url) {
            case "/":
                res.writeHead(200, {'Content-Type': 'text/html'});
                var index = getFileAsString("./sigserver/index.html");
                index = index.replace("theme-BLANK", "theme-" + getStorage("color_theme"));
                res.end(index);
                break;
            case "/bootstrap.min.css":
                res.writeHead(200, {'Content-Type': 'text/css'});
                res.end(getFileAsString("./css/bootstrap.min.css"));
                break;
            case "/theme.css":
                res.writeHead(200, {'Content-Type': 'text/css'});
                res.end(getFileAsString("./css/theme.css"));
                break;
            case "/fontawesome/all.min.js":
                res.writeHead(200, {'Content-Type': 'text/javascript'});
                res.end(getFileAsString("./node_modules/@fortawesome/fontawesome-free/js/all.min.js"));
                break;
            case "/signature_pad.umd.min.js":
                res.writeHead(200, {'Content-Type': 'text/javascript'});
                res.end(getFileAsString("./node_modules/signature_pad/dist/signature_pad.umd.min.js"));
                break;
            case "/img/signature-line.svg":
                res.writeHead(200, {'Content-Type': 'image/svg+xml'});
                res.end(getFileAsString("./img/signature-line.svg"));
                break;
            default:
                res.writeHead(404);
                res.end("404 not found.");
        }
    } else if (req.method == "POST") {
        var body = '';
        req.on('data', function (data) {
            body += data;
        });
        req.on('end', function () {
            handleRemoteSignatureData(JSON.parse(body));
        });
        res.writeHead(201);
    }
});
server.listen(http_port); //3 - listen for any incoming requests
console.log('Signature collection pad service running on port ' + http_port + '.');

function getSignatureServerUrl() {
    const prepareUrls = require('local-ip-url/prepareUrls');
    var urls = prepareUrls({
        protocol: 'http',
        host: '0.0.0.0',
        port: http_port
    });
    return urls.lanUrl;
}