import express from "express";
import mustache from "mustache";
import bodyParse from "body-parser";
import { readdirSync, readFileSync } from "fs";

const app = express();
app.use(express.static("./static"));
app.use(bodyParse.urlencoded({ extended: true }));
const port = 9559;

const data = JSON.parse(readFileSync("./goods.json", "utf-8"));
const templates = new Map(readdirSync("./templates").map(fn => [fn, readFileSync(`./templates/${fn}`, "utf-8")]));

app.get("/", (req, res) => {
    res.send(mustache.render(templates.get("mainPage.html"), data));
});

app.get("/category/:category", (req, res) => {
    const goodsForCategory = data.goods.filter(el => el.category === req.params.category);
    if (goodsForCategory.length === 0) {
        res.redirect("/");
    } else {
        res.send(mustache.render(templates.get("categoryPage.html"), { category: req.params.category, goods: goodsForCategory }));
    }
});

app.get("/goods/:goodUUID", (req, res) => {
    let good = null;
    let user = null;
    for (let _good of data.goods) {
        if (_good.guid !== req.params.goodUUID) continue;
        
        good = _good;
        break;
    }
    for (let _user of data.users) {
        if (_user.id !== good.uid) continue;

        user = _user;
        break;
    }
    if (good === null || user === null) {
        res.redirect("/");
    } else {
        res.send(mustache.render(templates.get("goodsPage.html"), { good, user }));
    }
});

app.get("/user/:userUUID", (req, res) => {
    let user = null;
    for (let _user of data.users) {
        if (_user.guid !== req.params.userUUID) continue;

        user = _user;
        break;
    }
    if (user === null) {
        res.redirect("/");
    } else {
        const goods = data.goods.filter(e => e.uid === user.id);
        res.send(mustache.render(templates.get("userPage.html"), { user, goods, goodsCount: goods.length }));
    }
});

app.post("/search", (req, res) => {
    const term = req.body.searchTerm.toLowerCase();
    const st = req.body.searchType;
    if (term === "") {
        res.redirect("/");
    } else {
        const showUsers = st === "usersOnly" || st === "both";
        const showGoods = st === "goodsOnly" || st === "both";
        const users = showUsers? data.users.filter(u => u.fullName.toLowerCase().includes(term)) : [];
        const goods = showGoods? data.goods.filter(e => e.title.toLowerCase().includes(term) || e.description.toLowerCase().includes(term)) : [];
        res.send(mustache.render(templates.get("searchPage.html"), { term, users, goods, showUsers, showGoods }));
    }
});

app.listen(port, () => console.log(`⚡️ Serving on port ${port}`));