const fs = require("fs");
const http = require("http");
const path = require("path");

var jsonUpdates = {};

const srv = http.createServer(process);
srv.listen(8000);
fs.watch(__dirname, trackJSONUpdates);

function process(req, res)
{
    var fileName = "." + decodeURI(req.url);
    if (fileName == "./")
    {
        fileName = "./index.html";
    }
    else if (fileName == "./json.js")
    {
        const content = Object.keys(jsonUpdates).sort().join("\n");
        jsonUpdates = {};
        res.writeHead(200, { "Content-Type": "text/javascript" });
        res.end(content, "utf-8");
        return;
    }
console.debug("fileName:", fileName);
    const ext = path.extname(fileName);
    var contentType = "text/html";
    switch (ext)
    {
        case ".js":
            contentType = "text/javascript";
            break;
        case "png":
            contentType = "image/png";
            break;
        case "jpg":
            contentType = "image/jpg";
            break;
        case "wav":
            contentType = "image/vnd.wave";
            break;
    }
    fs.readFile(fileName, function(err, content) {
        if (err)
        {
            res.writeHead(500);
            res.end(err.code);
            return;
        }
        res.writeHead(200, { "Content-Type": contentType });
        res.end(content, "utf-8");
    });
}

function trackJSONUpdates(eventName, fileName)
{
    if (!fileName.endsWith("json.js"))
    {
        return;
    }
    jsonUpdates[fileName] = true;
console.debug("fileName", fileName);
}

