// retoor <retoor@molodetz.nl>

import { Http } from "./Http.js";
import { JobPoller } from "./JobPoller.js";

export class ZipDownloader {
    constructor() {
        this.active = new Set();
        document.addEventListener("click", (event) => {
            const trigger = event.target.closest("[data-zip-download]");
            if (!trigger) return;
            event.preventDefault();
            this.start(trigger.dataset.zipDownload);
        });
    }

    async start(enqueueUrl) {
        if (this.active.has(enqueueUrl)) return;
        this.active.add(enqueueUrl);
        window.app.toast.show("Preparing download...", { type: "info", ms: 4000 });
        try {
            const job = await Http.postJson(enqueueUrl, {});
            await this.poll(job.status_url);
        } catch (err) {
            window.app.toast.show("Could not start the download", { type: "error" });
        } finally {
            this.active.delete(enqueueUrl);
        }
    }

    poll(statusUrl) {
        return JobPoller.run(statusUrl, {
            onDone: (status) => {
                this.trigger(status.download_url);
                window.app.toast.show("Download ready", { type: "success" });
            },
            onFailed: (status) => {
                window.app.toast.show("Zip failed: " + (status.error || "unknown error"), { type: "error" });
            },
            onTimeout: () => window.app.toast.show("Download timed out", { type: "error" }),
        });
    }

    trigger(url) {
        const link = document.createElement("a");
        link.href = url;
        link.download = "";
        document.body.appendChild(link);
        link.click();
        link.remove();
    }
}
