// retoor <retoor@molodetz.nl>

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

export class ContainerManager {
    constructor(root) {
        this.root = root;
        this.slug = root.dataset.slug;
        this.base = `/projects/${this.slug}/containers`;
        this.instances = [];
        this.pollMs = 3000;
    }

    init() {
        const dataNode = this.root.querySelector("#cm-data");
        let data = {};
        try {
            data = JSON.parse((dataNode && dataNode.textContent) || "{}");
        } catch (error) {
            data = {};
        }
        this.instances = data.instances || [];
        this.bind();
        this.renderInstances();
        this.poller = new Poller(() => this.refresh(), 20000, {
            immediate: false,
            pauseHidden: true,
        });
        const pubsub = window.app && window.app.pubsub;
        if (pubsub) {
            pubsub.subscribe(`project.${this.slug}.containers`, (payload) => {
                this.instances = payload.instances || [];
                this.renderInstances();
            });
        }
    }

    bind() {
        const instForm = document.getElementById("cm-new-instance-form");
        if (instForm) instForm.addEventListener("submit", (e) => { e.preventDefault(); this.createInstance(instForm); });
    }

    q(sel) { return this.root.querySelector(sel); }

    closeModal(id) {
        const modal = document.getElementById(id);
        if (modal) modal.classList.remove("visible");
    }

    toast(message, type) {
        if (window.app && window.app.toast) window.app.toast.show(message, { type: type || "info" });
    }

    async refresh() {
        const data = await Http.getJson(`${this.base}/data`);
        this.instances = data.instances || [];
        this.renderInstances();
    }

    renderInstances() {
        const list = this.q("#cm-instance-list");
        list.innerHTML = "";
        for (const inst of this.instances) {
            const li = document.createElement("li");
            li.className = "cm-item";
            const link = document.createElement("a");
            link.className = "cm-item-link";
            link.href = `/admin/containers/${inst.uid}`;
            const nameEl = document.createElement("span");
            nameEl.textContent = inst.name;
            const badge = document.createElement("span");
            badge.className = `cm-badge cm-${String(inst.status || "").replace(/[^a-z0-9_-]/gi, "")}`;
            badge.textContent = inst.status;
            link.append(nameEl, document.createTextNode(" "), badge);
            li.appendChild(link);
            list.appendChild(li);
        }
    }

    async createInstance(form) {
        const name = form.elements.name.value.trim();
        if (!name) return;
        try {
            await Http.send(`${this.base}/instances`, {
                name,
                boot_command: form.elements.boot_command.value.trim(),
                restart_policy: form.elements.restart_policy.value,
                ports: form.elements.ports.value.trim(),
                ingress_slug: form.elements.ingress_slug.value.trim(),
                ingress_port: form.elements.ingress_port.value.trim(),
                autostart: form.elements.autostart.checked ? "true" : "false",
            });
            this.closeModal("cm-new-instance-modal");
            form.reset();
            this.toast("Instance created", "success");
            await this.refresh();
        } catch (err) { this.toast(err.message, "error"); }
    }
}
