"use strict";

import { readFileSync } from "fs";
import { IncomingMessage, ServerResponse } from "http";
import { parse as urlParse } from "querystring";

/**
 * 
 * @param {ServerResponse} res 
 * @param {String} filename 
 * @param {Array.<Array.<String, Object>>} params 
 */
export function renderTemplate(res, filename, params = []) {
    let templateText = readFileSync(filename, "utf-8");
    params.forEach(el => {
        const [k, v] = el;
        templateText = templateText.replace(new RegExp(`\{\{${k}\}\}`, "g"), v);
    });
    res.writeHead(200, { "Content-Type": "text/html" });
    res.write(templateText);
    res.end();
}

/**
 * 
 * @param {IncomingMessage} req
 */
export function getCookies(req) {
    const list = {};
    const cookieHeader = req.headers?.cookie;
    if (!cookieHeader) return list;

    cookieHeader.split(";").forEach(function (cookie) {
        let [name, ...rest] = cookie.split("=");
        name = name?.trim();
        if (!name) return;
        const value = rest.join("=").trim();
        if (!value) return;
        list[name] = decodeURIComponent(value);
    });

    return list;
}

/**
 * 
 * @param {ServerResponse} res 
 * @param {Object} cookies 
 */
export function setCookies(res, cookies = {}) {
    res.setHeader(
        "Set-Cookie",
        Array.from(Object.keys(cookies))
            .map(e => `${encodeURIComponent(e)}=${encodeURIComponent(cookies[e])}`)
            .join(";")
    );
}

/**
 * 
 * @param {ServerResponse} res 
 * @param {String} path 
 */
export function redirect(res, path) {
    res.statusCode = 307;
    res.setHeader("Location", path);
    res.end();
}

export function consumePostForm(req) {
    return new Promise((resolve, reject) => {
        let body = "";
        req.on("data", function (data) {
            try {
                body += data;
                if (body.length > 1e6) {
                    req.destroy();
                }
            } catch (e) { reject(e); }
        });
        req.on("end", function () {
            try {
                const post = urlParse(body);
                resolve(post);
            } catch (e) { reject(e); }
        });
    });
}

