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

export function section_info_search() {
    return e("section", { class: "info" },
        e("h2", {}, "Setup"),
        e("p", {}, "To install this as the default search engine, select \"Add Fastbangs\" in the context-menu of the URL-bar.")
    )
}

export function section_search(engine: string) {
    link_engine(engine)

    bangs.then(bangs => {
        if (!bangs[engine.toLowerCase()]) {
            status("error", "Engine does not exist")
            window.location.hash = "#"
        }
    })

    const heading = e("h1", {}, engine)
    bangs.then(bangs => heading.textContent = bangs[engine]?.name ?? engine)

    const input = e("input", { type: "text" })
    input.addEventListener("keydown", ev => {
        if (ev.code == "Enter") {
            history.pushState({}, "", window.location.href)
            process_query(engine, input.value ?? "")
        }
    })

    const submit = e("button", {}, "Search")
    submit.addEventListener("click", () => {
        history.pushState({}, "", window.location.href)
        process_query(engine, input.value ?? "")
    })

    return e("section", { class: "search" },
        heading,
        e("div", { class: "bar" },
            input,
            submit
        )
    )
}

function link_engine(engine: string) {
    if (document.getElementById("search-link")) {
        // <link /> is already present, we need reload because browser wont notice otherwise
        window.location.reload()
    }
    const link = e("link", {
        rel: "search",
        id: "search-link",
        type: "application/opensearchdescription+xml",
        href: `search.xml?default=${encodeURIComponent(engine)}`,
        title: `Fastbangs (default engine: ${engine})`
    })
    document.head.append(link)
}
