var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { UmbEntityDataPickerInputContext } from './input-entity-data.context.js';
import { css, html, customElement, property, state, repeat, nothing, when, ifDefined, } from '../../../../external/lit/index.js';
import { splitStringToArray } from '../../../core/utils/index.js';
import { UmbChangeEvent } from '../../../core/event/index.js';
import { UmbLitElement } from '../../../core/lit-element/index.js';
import { UmbSorterController } from '../../../core/sorter/index.js';
import { UmbFormControlMixin } from '../../../core/validation/index.js';
let UmbInputEntityDataElement = class UmbInputEntityDataElement extends UmbFormControlMixin(UmbLitElement) {
    #sorter;
    set dataSourceApi(api) {
        this.#pickerInputContext.setDataSourceApi(api);
    }
    get dataSourceApi() {
        return this.#pickerInputContext.getDataSourceApi();
    }
    set dataSourceConfig(config) {
        this.#pickerInputContext.setDataSourceConfig(config);
    }
    get dataSourceConfig() {
        return this.#pickerInputContext.getDataSourceConfig();
    }
    set pickerViews(value) {
        this.#pickerInputContext.setPickerViews(value);
    }
    get pickerViews() {
        return this.#pickerInputContext.getPickerViews();
    }
    /**
     * This is a minimum amount of selected items in this input.
     * @type {number}
     * @attr
     * @default
     */
    set min(value) {
        this.#pickerInputContext.min = value;
    }
    get min() {
        return this.#pickerInputContext.min;
    }
    /**
     * This is a maximum amount of selected items in this input.
     * @type {number}
     * @attr
     * @default
     */
    set max(value) {
        this.#pickerInputContext.max = value;
    }
    get max() {
        return this.#pickerInputContext.max;
    }
    set selection(uniques) {
        this.#pickerInputContext.setSelection(uniques);
        this.#sorter.setModel(uniques);
    }
    get selection() {
        return this.#pickerInputContext.getSelection();
    }
    set value(selectionString) {
        this.selection = splitStringToArray(selectionString);
        super.value = selectionString; // Call the parent setter to ensure the value change is triggered in the FormControlMixin. [NL]
    }
    get value() {
        return this.selection.length > 0 ? this.selection.join(',') : undefined;
    }
    /**
     * Sets the input to readonly mode, meaning value cannot be changed but still able to read and select its content.
     * @type {boolean}
     * @attr
     * @default
     */
    get readonly() {
        return this.#readonly;
    }
    set readonly(value) {
        this.#readonly = value;
        if (this.#readonly) {
            this.#sorter.disable();
        }
        else {
            this.#sorter.enable();
        }
    }
    #readonly;
    #pickerInputContext;
    constructor() {
        super();
        this.#sorter = new UmbSorterController(this, {
            getUniqueOfElement: (element) => {
                return element.id;
            },
            getUniqueOfModel: (modelEntry) => {
                return modelEntry;
            },
            identifier: 'Umb.SorterIdentifier.InputEntityData',
            itemSelector: 'umb-entity-item-ref',
            containerSelector: 'uui-ref-list',
            onChange: ({ model }) => {
                this.selection = model;
                this.dispatchEvent(new UmbChangeEvent());
            },
        });
        /**
         * Min validation message.
         * @type {boolean}
         * @attr
         * @default
         */
        this.minMessage = 'This field need more items';
        /**
         * Max validation message.
         * @type {boolean}
         * @attr
         * @default
         */
        this.maxMessage = 'This field exceeds the allowed amount of items';
        this.#readonly = false;
        this._items = [];
        this.#pickerInputContext = new UmbEntityDataPickerInputContext(this);
        this.addValidator('rangeUnderflow', () => this.minMessage, () => !!this.min && this.#pickerInputContext.getSelection().length < this.min);
        this.addValidator('rangeOverflow', () => this.maxMessage, () => !!this.max && this.#pickerInputContext.getSelection().length > this.max);
        this.observe(this.#pickerInputContext.selection, (selection) => (this.value = selection.join(',')), '_observeSelection');
        this.observe(this.#pickerInputContext.selectedItems, (selectedItems) => (this._items = selectedItems), '_observerItems');
        this.observe(this.#pickerInputContext.statuses, (statuses) => (this._statuses = statuses), '_observerStatuses');
        this.observe(this.#pickerInputContext.modalRoute, (modalRoute) => {
            this._modalRoute = modalRoute;
        });
    }
    getFormElement() {
        return undefined;
    }
    #onRemove(unique) {
        this.#pickerInputContext.requestRemoveItem(unique);
    }
    render() {
        return html `${this.#renderItems()} ${this.#renderAddButton()}`;
    }
    #renderAddButton() {
        if (this.max > 0 && this.selection.length >= this.max)
            return nothing;
        if (this.readonly && this.selection.length > 0)
            return nothing;
        return html `
			<uui-button
				id="btn-add"
				look="placeholder"
				href=${ifDefined(this._modalRoute)}
				label="${this.localize.term('general_choose')}"
				?disabled=${this.readonly}></uui-button>
		`;
    }
    #renderItems() {
        if (!this._statuses)
            return;
        return html `
			<uui-ref-list>
				${repeat(this._statuses, (status) => status.unique, (status) => {
            const unique = status.unique;
            const item = this._items?.find((x) => x.unique === unique);
            return html `<umb-entity-item-ref
							id=${unique}
							.item=${item}
							?error=${status.state.type === 'error'}
							.errorMessage=${status.state.error}
							?readonly=${this.readonly}
							?standalone=${this.max === 1}>
							${when(!this.readonly, () => html `
									<uui-action-bar slot="actions">
										<uui-button
											label=${this.localize.term('general_remove')}
											@click=${() => this.#onRemove(unique)}></uui-button>
									</uui-action-bar>
								`)}
						</umb-entity-item-ref>`;
        })}
			</uui-ref-list>
		`;
    }
    static { this.styles = [
        css `
			#btn-add {
				width: 100%;
			}
		`,
    ]; }
};
__decorate([
    property({ type: Number })
], UmbInputEntityDataElement.prototype, "min", null);
__decorate([
    property({ type: String, attribute: 'min-message' })
], UmbInputEntityDataElement.prototype, "minMessage", void 0);
__decorate([
    property({ type: Number })
], UmbInputEntityDataElement.prototype, "max", null);
__decorate([
    property({ type: String, attribute: 'max-message' })
], UmbInputEntityDataElement.prototype, "maxMessage", void 0);
__decorate([
    property({ type: Array })
], UmbInputEntityDataElement.prototype, "selection", null);
__decorate([
    property({ type: String })
], UmbInputEntityDataElement.prototype, "value", null);
__decorate([
    property({ type: Boolean, reflect: true })
], UmbInputEntityDataElement.prototype, "readonly", null);
__decorate([
    state()
], UmbInputEntityDataElement.prototype, "_items", void 0);
__decorate([
    state()
], UmbInputEntityDataElement.prototype, "_statuses", void 0);
__decorate([
    state()
], UmbInputEntityDataElement.prototype, "_modalRoute", void 0);
UmbInputEntityDataElement = __decorate([
    customElement('umb-input-entity-data')
], UmbInputEntityDataElement);
export { UmbInputEntityDataElement };
