/* ===================== AUTOGENERATED SOURCE IMPORT ===================== */

import Template from "/emcJS/util/html/template/HTMLTemplate.js";

const TPL = new Template(`
    <div id="value">
        <p id="name"></p>
        <p id="type"></p>
    </div>
    <emc-select-relation id="input" nohover nopad>
        <slot></slot>
    </emc-select-relation>
    
`);

import GlobalStyle from "/emcJS/util/html/template/CSSTemplate.js";

const STYLE = new GlobalStyle(`
    :host([editable]:not([editable="false"])) #value {
        display: none;
    }
    
    :host([editable]:not([editable="false"])) #input {
        display: flex;
    }
    
    #value {
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        align-items: flex-start;
        overflow: hidden;
    }
    
    #value #name {
        font-size: 1em;
    }
    
    #value #type {
        font-size: 0.7em;
    }
    
    /* --- */
    #input {
        display: none;
        appearance: none;
        flex-grow: 0;
        width: 100%;
        min-width: 8em;
        height: 2em;
        margin-right: auto;
        font-size: 1rem;
    }
    
`);

/* ======================================================================= */

import {debounce} from "../../../../../../util/Debouncer.js";
import OptionGroupRegistry from "../../../../../../data/registry/form/OptionGroupRegistry.js";
import EventTargetManager from "../../../../../../util/event/EventTargetManager.js";
import DataGridCell from "../DataGridCell.js";
import "../../../../../form/element/select/relation/RelationSelect.js";

export default class DataGridCellRelation extends DataGridCell {

    #valueEl;

    #nameEl;

    #typeEl;

    #inputEl;

    #inputEventManager;

    #optionGroup = null;

    #optionGroupEventTargetManager = new EventTargetManager();

    constructor(dataGridId) {
        super(dataGridId);
        this.shadowRoot.getElementById("content").append(TPL.generate());
        STYLE.apply(this.shadowRoot);
        /* --- */
        this.#valueEl = this.shadowRoot.getElementById("value");
        this.#nameEl = this.shadowRoot.getElementById("name");
        this.#typeEl = this.shadowRoot.getElementById("type");
        this.#inputEl = this.shadowRoot.getElementById("input");
        /* --- */
        this.#inputEventManager = new EventTargetManager(this.#inputEl);
        this.#inputEventManager.set("input", (event) => {
            this.#onInput(event);
        });
    }

    set value(val) {
        this.setJSONAttribute("value", val);
    }

    get value() {
        return this.getJSONAttribute("value");
    }

    set optiongroup(value) {
        this.setAttribute("optiongroup", value);
    }

    get optiongroup() {
        return this.getAttribute("optiongroup");
    }

    static get observedAttributes() {
        return [...super.observedAttributes, "editable", "disabled", "readonly", "optiongroup"];
    }

    attributeChangedCallback(name, oldValue, newValue) {
        super.attributeChangedCallback(name, oldValue, newValue);
        if (oldValue != newValue) {
            switch (name) {
                case "editable": {
                    if (this.editable) {
                        this.#inputEventManager.active = true;
                    } else {
                        this.#inputEventManager.active = false;
                    }
                } break;
                case "disabled": {
                    this.#inputEl.disabled = this.disabled;
                } break;
                case "readonly": {
                    if (this.readonly) {
                        this.#inputEl.setAttribute("readonly", "");
                    } else {
                        this.#inputEl.removeAttribute("readonly");
                    }
                } break;
                case "optiongroup": {
                    if (newValue == null || newValue === "") {
                        this.#optionGroup = null;
                    } else {
                        this.#optionGroup = new OptionGroupRegistry(newValue);
                    }
                    this.#optionGroupEventTargetManager.switchTarget(this.#optionGroup);
                    this.#loadOptionsFromGroup();
                } break;
            }
        }
    }

    onValueChange(value) {
        if (value != null && typeof value.type === "string" && typeof value.name === "string" && value.type !== "" && value.name !== "") {
            this.#nameEl.innerText = value.name;
            this.#typeEl.innerText = value.type;
            this.#valueEl.title = `${value.name}\n[${value.type}]`;
            this.#inputEl.value = value;
        } else {
            this.#nameEl.innerText = "";
            this.#typeEl.innerText = "";
            this.#valueEl.title = "";
            this.#inputEl.value = value;
        }
    }

    #onInput = debounce((event) => {
        event.stopPropagation();
        event.preventDefault();
        const value = this.#inputEl.value;
        this.value = value;
        const ev = new Event("edit", {bubbles: true});
        ev.data = {
            value,
            action: this.action,
            columnName: this.columnName,
            rowKey: this.rowKey
        };
        this.dispatchEvent(ev);
    }, 300);

    #loadOptionsFromGroup() {
        this.innerHTML = "";
        if (this.#optionGroup != null) {
            for (const [value, label] of this.#optionGroup) {
                const optionEl = document.createElement("option");
                optionEl.setAttribute("value", value);
                if (typeof label === "string" && label !== "") {
                    optionEl.innerHTML = label;
                } else if (value !== "") {
                    optionEl.innerHTML = value;
                }
                this.append(optionEl);
            }
        }
    }

}

DataGridCell.registerCellType("relation", DataGridCellRelation, 300);
customElements.define("emc-datagrid-cell-relation", DataGridCellRelation);
