import { e } from "./helper.ts"

interface PendingBang {
    bang: string,
    name: string,
    url: string,
    email: string | undefined,
}

async function sendVerdict(user: string, pw: string, b: PendingBang,
                     accept: boolean, info_block: HTMLDivElement)
{
    let err = await fetch(accept? "acceptBang" : "rejectBang", {
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            Authorization: "Basic " + btoa(`${user}:${pw}`),
        },
        method: "POST",
        body: JSON.stringify(b)
    }).then(_ => null).catch(e => "" + e)

    if (err)
        info_block.appendChild(e("p", {class: "verdict-error"},
                                 "Something went wrong: " + await err))
    else
        info_block.remove()
    // TODO in the accept case, we should try invalidating the browser cache
    // for ./bangs.json. My idea is to make a HEAD request to let the browser
    // see that the etag has changed; idk of that works
}

export async function tryLoadAdminPanel(user: string, pw: string) {
    const r = await fetch("pendingBangs", {
        headers: {
            Accept: "application/json",
            Authorization: "Basic " + btoa(`${user}:${pw}`),
        }
    })
    if (!r.ok)
        throw (await r.json()).message

    const pending = await r.json() as PendingBang[]

    // it doesn't make sense to use a special url for the admin panel, as reloading
    // the page logs the user out anyway
    //@ts-ignore HTMLCollectionOf is an iterator
    for (const e of [...document.getElementsByTagName("section")]) e.remove()

    document.body.appendChild(e("section", {}, ...pending.map(b => {
        const btn_accept = e("button", {class: "pending-accept"}, "Accept")
        const btn_reject = e("button", {class: "pending-reject"}, "Reject")

        let r = e("div", {class: "pending-block"},
            e("span", {class: "pending-info"},
                e("p", {class: "pending-bang"}, "!" + b.bang),
                e("p", {class: "pending-name"}, b.name),
                e("p", {class: "pending-url"}, b.url),
                ...(b.email? [e("p", {class: "pending-email"}, b.email)] : [])
            ),
            btn_accept,
            btn_reject,
        )

        btn_accept.addEventListener("click", () => sendVerdict(user, pw, b,  true, r))
        btn_reject.addEventListener("click", () => sendVerdict(user, pw, b, false, r))

        return r
    })))
}
