import { e } from "./helper.ts"
import { bangs } from "./query.ts"
import { status } from "./ui.ts"

export function section_submit() {
    let skipped_warn = false
    const submit_button = e("button", {}, "Submit")
    const onchange = () => { skipped_warn = false; submit_button.textContent = "Submit" }
    const bang_input = e("input", { id: "i-bang", type: "text", onchange })
    const url_input = e("input", { id: "i-url", type: "url", onchange })
    const email_input = e("input", { id: "i-email", type: "email", onchange })
    const name_input = e("input", { id: "i-name", type: "text", onchange })

    submit_button.addEventListener("click", async () => {
        const [bang, url, email, name] = [bang_input.value, url_input.value, email_input.value, name_input.value]
        const w = []
        if (!url.includes("{{{s}}}")) w.push("URL does not include {{{s}}} pattern")
        if ((await bangs)[bang]) w.push("Bang already exists, it will be overwritten")
        if (!/^[A-Za-z0-9_-]+$/g.test(bang)) w.push("Bang has uncommon characters")

        if (w.length && !skipped_warn) {
            status("warn", w.join(", "))
            setTimeout(() => {
                submit_button.textContent = "Submit with warnings"
                skipped_warn = true
            }, 1000)
        } else {
            submit_bang({ bang, url, email, name })
            bang_input.disabled = true
            url_input.disabled = true
            email_input.disabled = true
            name_input.disabled = true
        }
    })

    return e("section", { class: "submit" },
        e("h1", {}, "Propose or change a bang"),
        e("p", {}, `
            Existing bangs with the same name will be overwritten.
            Use {{{s}}} in the URL in place of the search term.
            Proposals will come into effect after being approved by an administrator.
            If an email address is provided, you will be informed about the status of your proposal. (TODO email stuff not implemented)
        `),
        e("table", {},
            e("tr", {}, e("td", {}, e("label", {for: "i-name" }, "Website Name:"                 )), e("td", {}, name_input )),
            e("tr", {}, e("td", {}, e("label", {for: "i-bang" }, "Bang:"                         )), e("td", {}, bang_input )),
            e("tr", {}, e("td", {}, e("label", {for: "i-url"  }, "Search URL:"                   )), e("td", {}, url_input  )),
            e("tr", {}, e("td", {}, e("label", {for: "i-email"}, "Notification email (optional):")), e("td", {}, email_input))
        ),
        submit_button
    )
}

async function submit_bang(submission: { bang: string, url: string, name: string, email: string }) {
    status("info", "Submitting bang...")

    const r = await fetch(`submitBang`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
        },
        body: JSON.stringify(submission)
    })

    if (r.ok) status("success", "Submission successful")
    else status("error", "Submission failed")
}
