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

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

    private readonly rootDiv: HTMLDivElement;
    private linkOrButton: HTMLElement;

    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")!;
        this.linkOrButton = shadowRoot.querySelector<HTMLButtonElement>("button")!;
    }

    // noinspection JSUnusedGlobalSymbols
    attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null) {
        if (name === "disabled") {
            if (newValue === null) {
                this.linkOrButton.removeAttribute("disabled");
            } else {
                this.linkOrButton.setAttribute("disabled", "");
            }
        } else if (name === "href") {
            this.rootDiv.innerHTML = "";

            if (newValue) {
                this.linkOrButton = document.createElement("a");
                (this.linkOrButton as HTMLAnchorElement).href = newValue;
            } else {
                this.linkOrButton = document.createElement("button");
            }
            this.linkOrButton.part = "children";
            if (this.hasAttribute("disabled")) {
                this.linkOrButton.setAttribute("disabled", "");
            }
            this.rootDiv.appendChild(this.linkOrButton);

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

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

    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", "");
        }
    }

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

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