// retoor <retoor@molodetz.nl>

import { Http } from "./Http.js";
import { wireSearch, wireBootToggle } from "./ContainerFormControls.js";

export class ContainerEdit {
    constructor(form) {
        this.form = form;
        this.uid = form ? form.dataset.uid : "";
    }

    init() {
        if (!this.form) return;
        wireSearch(this.form, "user", "/admin/containers/users/search", "run_as_uid", (r) => r.uid, (r) => r.username);
        wireBootToggle(this.form);
        this.form.addEventListener("submit", (e) => { e.preventDefault(); this.save(); });
    }

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

    async save() {
        const f = this.form;
        const params = {
            run_as_uid: f.elements.run_as_uid.value.trim(),
            boot_language: f.elements.boot_language.value,
            boot_script: f.elements.boot_script.value,
            boot_command: f.elements.boot_command.value.trim(),
            restart_policy: f.elements.restart_policy.value,
            cpu_limit: f.elements.cpu_limit.value.trim(),
            mem_limit: f.elements.mem_limit.value.trim(),
            start_on_boot: f.elements.start_on_boot.checked ? "true" : "false",
        };
        try {
            await Http.send(`/admin/containers/${this.uid}/edit`, params);
            this.toast("Saved", "success");
            window.location.assign(`/admin/containers/${this.uid}`);
        } catch (err) {
            return;
        }
    }
}
