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

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

    private readonly button: TesoftButton;

    constructor() {
        super();

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

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

        this.button = shadowRoot.querySelector<TesoftButton>("tesoft-button")!;
    }

    // noinspection JSUnusedGlobalSymbols
    attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null) {
        if (name === "disabled") {
            setTimeout(() => {
                this.button.disabled = newValue;
            });
        } else if (name === "href") {
            setTimeout(() => {
                this.button.href = newValue ?? "";
            });
        } else if (name === "selected") {
            setTimeout(() => {
                this.button.selected = newValue;
            });
        }
    }

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

    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 small(value: string | null) {
        if (value === null) {
            this.removeAttribute("small");
        } else {
            this.setAttribute("small", "");
        }
    }
}

customElements.define("tesoft-tag", TesoftTag);
