class PragmaGroup extends HTMLElement {
    get title() {
        return this.getAttribute("title") || this._title;
    }

    set title(newValue) {
        this._title = newValue;
    }

    get expanded() {
        return this.getAttribute("expanded") || this._expanded;
    }

    set expanded(newValue) {
        this._expanded = newValue;
        if (newValue == "false") {
            this.classList.add("pragma-group-hidden");
        }
        else {
            this.classList.remove("pragma-group-hidden");
        }
    }

    constructor() {
        super();
        this.expanded = "true";
    }

    connectedCallback() {
        this.initTemplate();
        this.setGroupTitle();
        this.setToggleButton();
    }

    disconnectedCallback() {
        this.removeEventListener('click', this.toggleButtonElement);
    }

    static get observedAttributes() {
        return ["expanded"]; // array of string for attributes changing ["attribute1"]
    }

    attributeChangedCallback(name, oldValue, newValue) {
        if (name == "expanded") {
            this.expanded = newValue;
        }
    }

    initTemplate() {
        const instance = document.importNode(window.templates.get("pragma-group"), true);
        const body = this.querySelector(".pragma-group-body");
        this.insertBefore(instance, body);
    }

    setGroupTitle() {
        const h2Element = this.querySelector("h2");
        if (h2Element != undefined) {
            h2Element.innerText = this.title;
        }
    }

    setToggleButton() {
        this.toggleButtonElement = this.querySelector(".pragma-group-expand-button");
        if (this.toggleButtonElement != undefined) {
            this.toggleButtonElement.addEventListener("click", this.toggleGroup.bind(this))
        }
    }

    toggleGroup() {
        if (this.expanded == "false") {
            this.setAttribute("expanded", "true");
        }
        else {
            this.setAttribute("expanded", "false");
        }
    }
}

customElements.define('pragma-group', PragmaGroup);