// retoor <retoor@molodetz.nl>

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

export class WorkspaceManager {
    constructor(root) {
        this.root = root;
        this.slug = root.dataset.slug;
        this.poller = null;
        this.bind();
        this.subscribe();
    }

    static mount() {
        const root = document.querySelector("[data-workspace-root]");
        return root ? new WorkspaceManager(root) : null;
    }

    bind() {
        this.root.addEventListener("submit", (event) => {
            const form = event.target.closest("form");
            if (!form || form.dataset.confirm || form.dataset.native !== undefined) return;
            event.preventDefault();
            this.send(form);
        });
    }

    async send(form) {
        try {
            await Http.sendForm(form.action, this.params(form));
            await this.refresh();
        } catch (error) {
            window.app?.toast?.show(error.message || "Action failed", { type: "error" });
        }
    }

    params(form) {
        const params = [];
        new FormData(form).forEach((value, key) => params.push([key, value]));
        return params;
    }

    subscribe() {
        const uid = this.root.dataset.workspaceUid;
        if (uid && window.app?.pubsub) {
            window.app.pubsub.subscribe(`workspace.${uid}.detail`, () => this.render());
        }
        this.poller = new Poller(() => this.refresh(), 20000);
        this.poller.start();
    }

    async refresh() {
        try {
            const data = await Http.getJson(`/projects/${this.slug}/workspace`);
            this.render(data);
        } catch (error) {
            return;
        }
    }

    render(data) {
        if (!data || !data.workspace) return;
        const state = this.root.querySelector("[data-workspace-status]");
        if (state) state.textContent = data.workspace.status || "";
    }
}

export default WorkspaceManager;
