// retoor <retoor@molodetz.nl>

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

let confirmedThisSession = false;

class AvatarRegenerator {
    constructor() {
        this.btn = document.querySelector("[data-regenerate-avatar]");
        if (!this.btn) return;
        this.preview = document.getElementById("profile-avatar-preview");
        this.btn.addEventListener("click", () => this.regenerate());
    }

    async regenerate() {
        if (!confirmedThisSession) {
            const ok = await window.app.dialog.confirm({
                title: "Regenerate avatar",
                message: "A new random avatar will be generated. Your current avatar is gone for good and can never be brought back.",
                confirmLabel: "Regenerate",
                danger: true,
            });
            if (!ok) return;
            confirmedThisSession = true;
        }
        const username = this.btn.dataset.username;
        this.btn.disabled = true;
        try {
            const result = await Http.postJson(`/profile/${username}/regenerate-avatar`, {});
            const url = result && result.data ? result.data.avatar_url : "";
            if (!url) {
                Toast.flash(this.btn, "Error", 2000, "Regenerate avatar");
                return;
            }
            if (this.preview) this.preview.src = url;
            Toast.flash(this.btn, "Regenerated", 2000, "Regenerate avatar");
        } catch {
            Toast.flash(this.btn, "Error", 2000, "Regenerate avatar");
        } finally {
            this.btn.disabled = false;
        }
    }
}

window.AvatarRegenerator = AvatarRegenerator;
export { AvatarRegenerator };
