import {TesoftComponent} from "../scripts/main.ts";

export class TesoftButton extends TesoftComponent {
    static observedAttributes = ["disabled", "href", "selected"];

    private readonly rootDiv: HTMLDivElement;

    constructor() {
        super();

        const template = document.getElementById("tesoft-button-template") as HTMLTemplateElement;
        const templateContent = template.content;

        const shadowRoot = this.attachShadow({mode: "open"});
        shadowRoot.appendChild(templateContent.cloneNode(true));

        this.rootDiv = shadowRoot.querySelector<HTMLDivElement>("div")!;
    }

    // noinspection JSUnusedGlobalSymbols
    attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null) {
        if (name === "disabled") {
            if (newValue === null) {
                this.rootDiv.onclick = null;
            } else {
                this.rootDiv.onclick = (e) => {
                    e.stopPropagation();
                };
            }
        } else if (name === "href") {
            this.rootDiv.innerHTML = "";

            let linkOrButton: HTMLElement;
            if (newValue) {
                linkOrButton = document.createElement("a");
                (linkOrButton as HTMLAnchorElement).href = newValue;
            } else {
                linkOrButton = document.createElement("button");
            }
            linkOrButton.part = "children";
            this.rootDiv.appendChild(linkOrButton);

            const slot = document.createElement("slot");
            linkOrButton.appendChild(slot);
        }
    }

    get href(): string | null {
        return this.getAttribute("href");
    }

    set href(value: string | null) {
        if (value) {
            this.setAttribute("href", value);
        } else {
            this.removeAttribute("href");
        }
    }

    set selected(value: string | null) {
        if (value === null) {
            this.removeAttribute("selected");
        } else {
            this.setAttribute("selected", "");
        }
    }
}

customElements.define("tesoft-button", TesoftButton);
