const api = require("./api.js"),
app = require("./expressHandler.js").app,
showdown = require("showdown"),
pageUpdater = require("./pageUpdater.js"),
fs = require("fs"),
path = require("path")
mkhtml = new showdown.Converter()

mkhtml.setFlavor("github")

app.use((req, res, next) => {
    if (req.path.includes("blog") && api.blogPosts) {
        var postName = decodeURIComponent(req.path.substring(6, req.path.length - 1))
        for (var i = 0; i < api.blogPosts.length; i++) {
            var post = api.blogPosts[i]

            if (post.folder == postName || post.folder == decodeURIComponent(post.title)) {
                var mkdwn = post.data
                var html = mkhtml.makeHtml(mkdwn)

                html = fs.readFileSync(path.join(__dirname, "assets/html/blog.html")).toString().replace("{BLOG_POST}", html)

                html = pageUpdater.converter(html, false)

                html = html.replaceAll("{BLOG_TITLE}", post.title)
                html = html.replaceAll("{BLOG_DESC}", post.desc)

                res.send(html)
                return
            }
        }
        next()
    } else {
        next()
    }
})