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

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

const TPL = new Template(`
    <div id="icon-background">
        <div id="icon"></div>
    </div>
    <input is="emc-i18n-input" id="input" type="text" readonly tabindex="-1">
    <emc-i18n-tooltip i18n-tooltip="choose">
        <button id="button"></button>
    </emc-i18n-tooltip>
    <slot id="options-slot"></slot>
    
`);

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

const STYLE = new GlobalStyle(`
    #icon-background {
        width: 2em;
        height: 2em;
        margin-right: calc(-1 * var(--input-border-width, 2px));
        background-color: var(--input-back-color, #ffffff);
        background-image:
            linear-gradient(45deg, var(--image-checker-back-color) 25%, transparent 25%),
            linear-gradient(-45deg, var(--image-checker-back-color) 25%, transparent 25%),
            linear-gradient(45deg, transparent 75%, var(--image-checker-back-color) 75%),
            linear-gradient(-45deg, transparent 75%, var(--image-checker-back-color) 75%);
        background-size: 10px 10px;
        background-position: 0 0, 0 5px, 5px -5px, -5px 0;
        border-style: solid;
        border-width: var(--input-border-width, 2px);
        border-color: var(--input-border-color, #222222);
        border-radius: var(--input-border-radius, 6px) 0px 0px var(--input-border-radius, 6px);
    }
    
    :host(:invalid) #icon-background {
        background-color: var(--input-invalid-back-color, #ffebeb);
        border-color: var(--input-invalid-border-color, #ff4444);
    }
    
    #icon {
        width: 100%;
        height: 100%;
        font-size: 1em;
        background-size: contain;
        background-repeat: no-repeat;
        background-position: center;
    }
    
    /* --- */
    #input {
        flex-grow: 1;
        height: 2em;
        padding: 0px 7px;
        color: var(--input-text-color, #000000);
        background-color: var(--input-back-color, #ffffff);
        background-image: var(--input-back-image, none);
        border-style: solid;
        border-width: var(--input-border-width, 2px);
        border-color: var(--input-border-color, #222222);
        border-radius: 0px;
        font-size: 1em;
        pointer-events: none;
    }
    
    #input:focus {
        box-shadow: 0 0 2px 3px var(--input-focus-color, #06b5ff);
        outline: none;
        z-index: 1;
    }
    
    :host(:invalid) #input {
        color: var(--input-invalid-text-color, #000000);
        background-color: var(--input-invalid-back-color, #ffebeb);
        background-image: var(--input-invalid-back-image, none);
        border-color: var(--input-invalid-border-color, #ff4444);
    }
    
    :host(:invalid) #input:focus {
        box-shadow: 0 0 2px 3px var(--input-invalid-focus-color, #ff2500);
    }
    
    #input::placeholder {
        color: var(--input-placeholder-text-color, #757575);
    }
    
    #input:disabled {
        color: var(--input-disabled-text-color, #757575) !important;
        background-color: var(--input-disabled-back-color, #999999) !important;
        background-image: var(--input-disabled-back-image, none) !important;
        border-color: var(--input-disabled-border-color, #6a6a6a) !important;
        cursor: default !important;
    }
    
    /* --- */
    #button {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 2em;
        height: 2em;
        padding: 0px;
        margin: 0 0 0 calc(-1 * var(--input-border-width, 2px));
        color: var(--input-button-text-color, #000000);
        background-color: var(--input-button-back-color, #ffffff);
        background-image: var(--input-button-back-image, none);
        border-style: solid;
        border-width: var(--input-border-width, 2px);
        border-color: var(--input-border-color, #222222);
        border-radius: 0 var(--input-border-radius, 6px) var(--input-border-radius, 6px) 0;
        font-size: 1rem;
        font-weight: bold;
        cursor: pointer;
        appearance: none;
    }
    
    #button:hover {
        color: var(--input-button-hover-text-color, #000000);
        background-color: var(--input-button-hover-back-color, #b3e5ec);
        background-image: var(--input-button-hover-back-image, none);
    }
    
    #button:focus {
        box-shadow: 0 0 2px 3px var(--input-focus-color, #06b5ff);
        outline: none;
        z-index: 1;
    }
    
    :host(:invalid) #button {
        color: var(--input-button-invalid-text-color, #000000);
        background-color: var(--input-button-invalid-back-color, #ffebeb);
        background-image: var(--input-button-invalid-back-image, none);
        border-color: var(--input-invalid-border-color, #ff4444);
    }
    
    :host(:invalid) #button:hover {
        color: var(--input-button-invalid-hover-text-color, #000000);
        background-color: var(--input-button-invalid-hover-back-color, #ff9987);
        background-image: var(--input-button-invalid-hover-back-image, none);
    }
    
    :host(:invalid) #button:focus {
        box-shadow: 0 0 2px 3px var(--input-invalid-focus-color, #ff2500);
    }
    
    #button:disabled {
        color: var(--input-button-disabled-text-color, #757575) !important;
        background-color: var(--input-button-disabled-back-color, #999999) !important;
        background-image: var(--input-button-disabled-back-image, none) !important;
        border-color: var(--input-disabled-border-color, #6a6a6a) !important;
        cursor: default !important;
    }
    
    #button::before {
        position: absolute;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        margin-left: -4px;
        font-family: monospace;
        font-size: 1.2em;
        line-height: 1em;
        letter-spacing: -4px;
        content: "...";
    }
    
    #options-slot {
        display: none !important;
    }
    
`);

const CONFIG_FIELDS = [
    {
        "type": "StringInput",
        "name": "placeholder",
        "label": "Placeholder",
        "value": ""
    },
    {
        "type": "SwitchInput",
        "name": "sorted",
        "label": "Sorted",
        "value": false
    },
    {
        "type": "KeyValueListInput",
        "name": "options",
        "label": "Options",
        "value": {}
    },
    {
        "type": "StringInput",
        "name": "optiongroup",
        "label": "Option Group",
        "value": ""
    }
]
;

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

import AbstractFormElement from "../../AbstractFormElement.js";
import FormElementRegistry from "../../../../../data/registry/form/FormElementRegistry.js";
import BusyIndicatorManager from "../../../../../util/BusyIndicatorManager.js";
import EventTargetManager from "../../../../../util/event/EventTargetManager.js";
import {deepClone} from "../../../../../util/helper/DeepClone.js";
import {debounce} from "../../../../../util/Debouncer.js";
import {nodeTextComparator} from "../../../../../util/helper/ui/NodeListSort.js";
import {registerFocusable} from "../../../../../util/helper/html/ElementFocusHelper.js";
import {safeSetAttribute} from "../../../../../util/helper/ui/NodeAttributes.js";
import MutationObserverManager from "../../../../../util/observer/manager/MutationObserverManager.js";
import ImageSelectModal from "./components/ImageSelectModal.js";
import I18nOption from "../../../../i18n/builtin/I18nOption.js";
import i18n from "../../../../../util/I18n.js";
import ImageSelectPreviewManager from "./components/ImageSelectPreviewManager.js";

const MUTATION_CONFIG = {
    attributes: true,
    attributeFilter: ["value", "label"]
};

// TODO use option slot like the other select elements
export default class ImageSelect extends AbstractFormElement {

    static get formConfigurationFields() {
        return [...super.formConfigurationFields, ...deepClone(CONFIG_FIELDS)];
    }

    static get changeDebounceTime() {
        return 0;
    }

    #iconEl;

    #inputEl;

    #buttonEl;

    #optionsSlotEl;

    #imageIconModal = new ImageSelectModal();

    #i18nEventManager = new EventTargetManager(i18n);

    #mutationObserver = new MutationObserverManager(MUTATION_CONFIG, () => {
        this.#onSlotChange();
    });

    #imageSelectPreviewManager;

    constructor() {
        super();
        this.shadowRoot.getElementById("field").append(TPL.generate());
        STYLE.apply(this.shadowRoot);
        /* --- */
        this.#iconEl = this.shadowRoot.getElementById("icon");
        this.#inputEl = this.shadowRoot.getElementById("input");
        this.#inputEl.addEventListener("focus", () => {
            this.#buttonEl.focus();
        });
        this.#buttonEl = this.shadowRoot.getElementById("button");
        this.#buttonEl.addEventListener("click", () => {
            this.#imageIconModal.value = this.value;
            this.#imageIconModal.onsubmit = () => {
                this.value = this.#imageIconModal.value;
            };
            this.#imageIconModal.show();
        });
        this.#optionsSlotEl = this.shadowRoot.getElementById("options-slot");
        this.#optionsSlotEl.addEventListener("slotchange", () => {
            this.#onSlotChange();
        });
        /* --- */
        this.#imageSelectPreviewManager = new ImageSelectPreviewManager(this.#imageIconModal);
        this.#imageSelectPreviewManager.addEventListener("afterrender", () => {
            this.renderValue(this.value);
        });
        /* --- */
        this.#i18nEventManager.active = this.getBooleanAttribute("sorted");
        this.#i18nEventManager.set("language", () => {
            this.#imageSelectPreviewManager.sort();
        });
        this.#i18nEventManager.set("translation", () => {
            this.#imageSelectPreviewManager.sort();
        });
    }

    formDisabledCallback(disabled) {
        super.formDisabledCallback(disabled);
        this.#inputEl.disabled = disabled;
    }

    validityCallback(message) {
        this.#inputEl.setCustomValidity(message);
    }

    focus(options) {
        this.#inputEl.focus(options);
    }

    set value(value) {
        this.#inputEl.value = value ?? this.defaultValue;
        super.value = value;
    }

    get value() {
        return super.value;
    }

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

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

    set sorted(value) {
        this.setBooleanAttribute("sorted", value);
    }

    get sorted() {
        return this.getBooleanAttribute("sorted");
    }

    static get observedAttributes() {
        return [...super.observedAttributes, "placeholder", "readonly", "sorted"];
    }

    attributeChangedCallback(name, oldValue, newValue) {
        super.attributeChangedCallback(name, oldValue, newValue);
        switch (name) {
            case "placeholder": {
                if (oldValue != newValue) {
                    safeSetAttribute(this.#inputEl, "i18n-placeholder", newValue);
                }
            } break;
            case "readonly": {
                if (oldValue != newValue) {
                    safeSetAttribute(this.#inputEl, name, newValue);
                }
            } break;
            case "sorted": {
                if (oldValue != newValue) {
                    const sorted = this.sorted;
                    if (sorted) {
                        this.#imageSelectPreviewManager.registerSortFunction(this.#sortByNameFunction);
                    } else {
                        this.#imageSelectPreviewManager.registerSortFunction();
                    }
                }
            } break;
        }
    }

    renderValue(value) {
        if (value != null && value !== "") {
            this.#iconEl.style.backgroundImage = `url(${value})`;
            this.#inputEl.value = value;
        } else {
            this.#iconEl.style.backgroundImage = "";
            this.#inputEl.value = "";
        }
    }

    #onSlotChange = debounce(async () => {
        await BusyIndicatorManager.busy();
        const data = [];
        const optionNodeList = this.#optionsSlotEl.assignedElements({flatten: true}).filter((el) => el.matches("option"));
        /* --- */
        const oldNodes = new Set(this.#mutationObserver.getObservedNodes());
        const newNodes = new Set();
        for (const el of optionNodeList) {
            data.push({
                key: el.value || el.innerText,
                label: el.i18nValue || el.label || el.innerText
            });
            /* --- */
            if (oldNodes.has(el)) {
                oldNodes.delete(el);
            } else {
                newNodes.add(el);
            }
        }
        for (const node of oldNodes) {
            this.#mutationObserver.unobserve(node);
        }
        for (const node of newNodes) {
            this.#mutationObserver.observe(node);
        }
        /* --- */
        this.#imageSelectPreviewManager.manage(data);
        /* --- */
        this.renderValue(this.value);
        await BusyIndicatorManager.unbusy();
    });

    #sortByNameFunction(entry0, entry1) {
        const {element: el0} = entry0;
        const {element: el1} = entry1;
        return nodeTextComparator(el0, el1);
    }

    static fromConfig(config) {
        const selectEl = new ImageSelect();
        const {
            options = {}, ...params
        } = config;

        for (const key in options) {
            const value = options[key];
            const optionEl = I18nOption.create();
            optionEl.value = key;
            optionEl.i18nValue = value;
            selectEl.append(optionEl);
        }

        for (const name in params) {
            const value = params[name];
            safeSetAttribute(selectEl, name, value);
        }

        return selectEl;
    }

}

FormElementRegistry.register("ImageSelect", ImageSelect);
customElements.define("emc-select-image", ImageSelect);
registerFocusable("emc-select-image");
