"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fastify_plugin_1 = __importDefault(require("fastify-plugin"));
const path_1 = __importDefault(require("path"));
const static_1 = __importDefault(require("@fastify/static"));
const env_1 = require("../env");
const fs_1 = __importDefault(require("fs"));
exports.default = (0, fastify_plugin_1.default)(async function staticPlugin(fastify) {
    const webRoot = path_1.default.resolve(__dirname, "../../www/browser");
    const dataDir = env_1.env.dataDir;
    const spritesRoot = path_1.default.join(env_1.env.dataDir, "cache", "sprites");
    for (const dir of [dataDir]) {
        if (!fs_1.default.existsSync(dir))
            fs_1.default.mkdirSync(dir, { recursive: true });
    }
    fastify.log.info(`[static] serving webapp from ${webRoot}`);
    fastify.log.info(`[static] dataDir=${dataDir}`);
    fastify.log.info(`[static] serving sprites from ${spritesRoot} `);
    await fastify.register(static_1.default, {
        root: webRoot,
        index: "index.html",
        decorateReply: true,
    });
    await fastify.register(static_1.default, {
        root: spritesRoot,
        prefix: "/sprites/",
        decorateReply: false,
    });
    fastify.setNotFoundHandler((req, reply) => {
        const url = req.url || "";
        const isSpaFallbackCandidate = req.method === "GET" &&
            !url.startsWith("/api") &&
            !url.startsWith("/ws") &&
            !url.startsWith("/sprites/");
        if (isSpaFallbackCandidate) {
            return reply.sendFile("index.html");
        }
        reply.code(404).send({ ok: false, message: "Not Found" });
    });
});
