// retoor <retoor@molodetz.nl>

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

export class ProjectForker {
    constructor() {
        this.active = new Set();
        document.addEventListener("click", (event) => {
            const trigger = event.target.closest("[data-fork-project]");
            if (!trigger) return;
            event.preventDefault();
            this.start(trigger.dataset.forkProject, trigger.dataset.forkName || "");
        });
    }

    async start(enqueueUrl, sourceName) {
        if (this.active.has(enqueueUrl)) return;
        const title = await window.app.dialog.prompt({
            title: "Fork project",
            label: "New project name",
            value: sourceName ? `${sourceName} (fork)` : "",
            confirmLabel: "Fork",
        });
        if (title === null) return;
        const name = title.trim();
        if (!name) {
            window.app.toast.show("A project name is required", { type: "error" });
            return;
        }
        this.active.add(enqueueUrl);
        window.app.toast.show("Forking project...", { type: "info", ms: 4000 });
        try {
            const job = await Http.sendForm(enqueueUrl, { title: name });
            await this.poll(job.status_url);
        } catch (err) {
            window.app.toast.show("Could not start the fork", { type: "error" });
        } finally {
            this.active.delete(enqueueUrl);
        }
    }

    poll(statusUrl) {
        return JobPoller.run(statusUrl, {
            onDone: (status) => {
                window.app.toast.show("Fork ready", { type: "success" });
                window.location.href = status.project_url;
            },
            onFailed: (status) => {
                window.app.toast.show("Fork failed: " + (status.error || "unknown error"), { type: "error" });
            },
            onTimeout: () => window.app.toast.show("Fork timed out", { type: "error" }),
        });
    }
}
