/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/
/// <reference lib="dom" />

import { OVar } from "./jshelper/mod.ts";
import { e } from "./jshelper/src/element.ts";

interface ImportProgress {
    total_items: number
    finished_items: number
    tasks: string[]
}

function progress_bar(progress: OVar<number>, text: OVar<string>): HTMLElement {
    const bar_inner = e("div")
    bar_inner.style.height = "100%"
    bar_inner.style.backgroundColor = "#444"
    bar_inner.style.position = "absolute"
    bar_inner.style.top = "0px"
    bar_inner.style.left = "0px"
    bar_inner.style.zIndex = "2"
    const bar_text = e("div")
    bar_text.style.position = "absolute"
    bar_text.style.top = "0px"
    bar_text.style.left = "0px"
    bar_text.style.color = "white"
    bar_text.style.zIndex = "3"
    const bar_outer = e("div", bar_inner, bar_text)
    bar_outer.style.position = "relative"
    bar_outer.style.width = "100%"
    bar_outer.style.height = "2em"
    bar_outer.style.backgroundColor = "black"
    bar_outer.style.borderRadius = "5px"
    progress.onchangeinit(v => bar_inner.style.width = `${v * 100}%`)
    text.onchangeinit(v => bar_text.textContent = v)
    return bar_outer
}

globalThis.addEventListener("DOMContentLoaded", () => {
    if (!document.getElementById("admin_import")) return
    const el = document.getElementById("admin_import")!

    const ws = new WebSocket(`/admin/import`)
    ws.onopen = () => console.log("live progress connected");
    ws.onclose = () => console.log("live progress disconnected");
    ws.onerror = e => console.log("live progress ws error", e);


    const progress = new OVar(0)
    const text = new OVar("")
    const pre = e("pre")
    el.append(progress_bar(progress, text), pre)

    ws.onmessage = msg => {
        if (msg.data == "done") return location.reload()
        const p: ImportProgress = JSON.parse(msg.data)
        text.value = `${p.finished_items} / ${p.total_items}`
        progress.value = p.finished_items / p.total_items
        pre.textContent = p.tasks.map((e, i) => `thread ${("#" + i).padStart(3)}: ${e}`).join("\n")
    }
})
