import { app, fs, globalVersion } from "../index.js"
import { parseKbas } from "../liberals/directoryparsing.js"
import { marked } from "marked"

var timeSinceLastQuery = Date.now()-10000
var cachedResult = ""
app.get("/helpdesk*", (rreq, rres) => {
    if (Date.now() < timeSinceLastQuery+10000) {
        rres.send(cachedResult)
    } else {
        let indexFile = fs.readFileSync(process.cwd()+"/website/templates/unavailable.html","utf-8")
        cachedResult = indexFile.replace("<!--SSR_APIVERSION-->",`<sup>Build ${globalVersion}</sup>`)
        rres.send(cachedResult)
    }
})

// app.get("/helpdesk", (rreq, rres) => {
//     rres.sendFile(process.cwd()+"/website/helpdesk/templates/landing.html")
// })

// app.get("/helpdesk/articles", (rreq, rres) => {
//     let file = fs.readFileSync(process.cwd() + "/website/helpdesk/templates/article.html", "utf-8")
//     file = file.replace("<!--SSR_REPLACE_URL-->", `https://enstrayed.com${rreq.url}`)
//     file = file.replaceAll("<!--SSR_REPLACE_TITLE-->", "Knowledgebase")
//     file = file.replace("<!--SSR_REPLACE_BODY-->", parseKbas())
//     rres.send(file)
// })

// app.get("/helpdesk/articles/*", (rreq, rres) => {
//     if (rreq.url.endsWith(".md")) {
//         let file = fs.readFileSync(process.cwd() + "/website/helpdesk/templates/article.html", "utf-8")
//         file = file.replace("<!--SSR_REPLACE_URL-->", `https://enstrayed.com${rreq.url}`)
//         file = file.replaceAll("<!--SSR_REPLACE_TITLE-->", rreq.url.replace("/helpdesk/articles/", "").replace(/(-|_)/g, " ").replace(".md", ""))
//         file = file.replace("<!--SSR_REPLACE_BODY-->", marked.parse(fs.readFileSync(process.cwd() + "/website/helpdesk/kbas/" + rreq.url.replace("/helpdesk/articles/", ""), "utf-8")))
//         rres.send(file)
//     } else {
//         rres.sendFile(process.cwd() + "/website/helpdesk/kbas" + rreq.url.replace("/helpdesk/articles/", ""))
//     }
// })

// app.get("/helpdesk/ticket/new", (rreq,rres) => {
//     rres.sendFile(process.cwd()+"/website/helpdesk/templates/newticket.html")
// })

// app.get("/api/helpdesk/forms/*", (rreq, rres) => {
//     fs.readFile(process.cwd()+"/website/helpdesk/forms/"+rreq.url.replace("/api/helpdesk/forms/","")+".json","utf-8", (error, data) => {
//         if (error) {
//             rres.status(400).send("Unable to retrieve requested form")
//         } else {
//             rres.type('json').send(data)
//         }
//     })

// })

// app.get("/helpdesk/static/*", (rreq,rres) => {
//     rres.sendFile(process.cwd()+"/website/helpdesk/static/"+rreq.url.replace("/helpdesk/static/",""))
// })

export { app }