import { auth, config, method, route, swagger, validate } from "@noderun/hapi-router"
import { Req, Res, ReturnValue } from "#/global"
import path from "path"
import fs from "fs-extra"
import { baseDir, gFail, sourceDir } from "@/util"
import MarkdownIt from "markdown-it"

export default class Index {
    @auth("try")
    async index(request: Req, h: Res): ReturnValue {
        const isRenderHtmx = Reflect.has(request.query, "htmx")
        if (isRenderHtmx) {
            return h.view("htmx/path/index.pug", { isLogin: request.auth.isAuthenticated })
        }
        return h.view("views/index.pug", { isLogin: request.auth.isAuthenticated })
    }

    @route("/about")
    @auth("try")
    async about(request: Req, h: Res) {
        const isRenderHtmx = Reflect.has(request.query, "htmx")
        if (!request.auth.isAuthenticated) {
            if (isRenderHtmx) {
                // https://github.com/hapijs/hapi/issues/4443
                // https://github.com/hapijs/hapi/issues/4212
                return h.response().header("HX-Redirect", `/login?next=${encodeURIComponent(request.path)}`)
            }
            return h.redirect(`/login?next=${encodeURIComponent(request.path)}`).takeover()
        }
        const md = new MarkdownIt()
        console.log(path.resolve(baseDir, "./docs/a.md"));
        
        var result = md.render(fs.readFileSync(path.resolve(baseDir, "./docs/a.md"), "utf-8"))
        const data = {
            md: result
        }
        if (isRenderHtmx) {
            return h.view("htmx/path/about.pug", data)
        }
        return h.view("views/about.pug", data)
    }

    @route("/docs/{path*}")
    @auth()
    async docs(req: Req, h: Res): ReturnValue {
        //   const {id} = req.auth.credentials
        //   try {
        //     req.cookieAuth.ttl(720 * 24 * 60 * 60 * 1000)
        //     req.cookieAuth.set({ id: id });
        //   } catch (error) {
        //       console.log(error);

        //   }
        if (req.params && req.params.path.endsWith(".md")) {
            //   console.log(path.resolve(baseDir, "docs/"+"*.md"));
            //   console.log(await glob("docs/"+"*.md"));
            const mdPath = path.resolve(baseDir, "docs/" + req.params.path)
            if (fs.existsSync(mdPath)) {
                const str = fs.readFileSync(mdPath, "utf8")
                console.log("---->", mdPath)

                return h.view("views/css.pug", {
                    content: str.toString(),
                })
            }
            // 解析文档
            return h.view("views/css.pug")
        }
        // 404页面
        return h.redirect("/404")
    }
    @route("/{path*}")
    async any(req: Req, h: Res): ReturnValue {
        if (req.path) {
            const filePath = path.resolve(baseDir, "template/views", "."+req.path+".pug")
            if(fs.existsSync(filePath)){
                return h.view(`views${req.path}.pug`)
            }
        }
        console.log("404: ", req.raw.req.url)
        return h.redirect("/404?r=" + encodeURIComponent(req.raw.req.url))
    }
    @route("/404")
    @auth("try")
    async 404(request: Req, h: Res): ReturnValue {
        if (request.auth.isAuthenticated) {
            // 登录了
        } else {
            // 未登录
        }
        if (request.query?.r) {
            // 可重定向返回
        }
        return h.view("404.pug", {
            rollback: request.query?.r,
        })
    }
}