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 { UmbMediaTypePickerInputContext } from './input-media-type.context.js';
import { css, customElement, html, nothing, property, repeat, state } from '../../../../../external/lit/index.js';
import { splitStringToArray } from '../../../../core/utils/index.js';
import { UmbChangeEvent } from '../../../../core/event/index.js';
import { UmbFormControlMixin } from '../../../../core/validation/index.js';
import { UmbLitElement } from '../../../../core/lit-element/index.js';
import { UmbModalRouteRegistrationController } from '../../../../core/router/index.js';
import { UmbSorterController } from '../../../../core/sorter/index.js';
import { UMB_WORKSPACE_MODAL } from '../../../../core/workspace/index.js';
import '../../../../core/entity-item/index.js';
let UmbInputMediaTypeElement = class UmbInputMediaTypeElement extends UmbFormControlMixin(UmbLitElement) {
    #sorter;
    /**
     * This is a minimum amount of selected items in this input.
     * @type {number}
     * @attr
     * @default
     */
    set min(value) {
        this.#pickerContext.min = value;
    }
    get min() {
        return this.#pickerContext.min;
    }
    /**
     * This is a maximum amount of selected items in this input.
     * @type {number}
     * @attr
     * @default
     */
    set max(value) {
        this.#pickerContext.max = value;
    }
    get max() {
        return this.#pickerContext.max;
    }
    set selection(uniques) {
        this.#pickerContext.setSelection(uniques);
        this.#sorter.setModel(uniques);
    }
    get selection() {
        return this.#pickerContext.getSelection();
    }
    set value(selectionString) {
        this.selection = splitStringToArray(selectionString);
    }
    get value() {
        return this.selection.length > 0 ? this.selection.join(',') : undefined;
    }
    #pickerContext;
    constructor() {
        super();
        this.#sorter = new UmbSorterController(this, {
            getUniqueOfElement: (element) => {
                return element.id;
            },
            getUniqueOfModel: (modelEntry) => {
                return modelEntry;
            },
            identifier: 'Umb.SorterIdentifier.InputMediaType',
            itemSelector: 'uui-ref-node-document-type',
            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._editPath = '';
        this.#pickerContext = new UmbMediaTypePickerInputContext(this);
        new UmbModalRouteRegistrationController(this, UMB_WORKSPACE_MODAL)
            .addAdditionalPath('media-type')
            .onSetup(() => {
            return { data: { entityType: 'media-type', preset: {} } };
        })
            .observeRouteBuilder((routeBuilder) => {
            this._editPath = routeBuilder({});
        });
        this.addValidator('rangeUnderflow', () => this.minMessage, () => !!this.min && this.#pickerContext.getSelection().length < this.min);
        this.addValidator('rangeOverflow', () => this.maxMessage, () => !!this.max && this.#pickerContext.getSelection().length > this.max);
        this.observe(this.#pickerContext.selection, (selection) => (this.value = selection.join(',')), '_observeSelection');
        this.observe(this.#pickerContext.selectedItems, (selectedItems) => (this._items = selectedItems), '_observerItems');
        this.observe(this.#pickerContext.statuses, (statuses) => (this._statuses = statuses), '_observeStatuses');
    }
    getFormElement() {
        return undefined;
    }
    #getPickableFilter() {
        return (x) => !x.isFolder;
    }
    #openPicker() {
        this.#pickerContext.openPicker({
            hideTreeRoot: true,
            pickableFilter: this.#getPickableFilter(),
        });
    }
    #removeItem(unique) {
        this.#pickerContext.requestRemoveItem(unique);
    }
    render() {
        return html `${this.#renderItems()} ${this.#renderAddButton()}`;
    }
    #renderAddButton() {
        if (this.max > 0 && this.selection.length >= this.max)
            return nothing;
        return html `
			<uui-button
				id="btn-add"
				look="placeholder"
				@click=${this.#openPicker}
				label="${this.localize.term('general_choose')}"></uui-button>
		`;
    }
    #renderItems() {
        if (!this._statuses)
            return nothing;
        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);
            const isError = status.state.type === 'error';
            // For error state, use umb-entity-item-ref
            if (isError) {
                return html `
								<umb-entity-item-ref
									id=${unique}
									.item=${item}
									?error=${true}
									.errorMessage=${status.state.error}
									.errorDetail=${unique}
									?standalone=${this.max === 1}>
									<uui-action-bar slot="actions">
										<uui-button
											label=${this.localize.term('general_remove')}
											@click=${() => this.#removeItem(unique)}></uui-button>
									</uui-action-bar>
								</umb-entity-item-ref>
							`;
            }
            // For successful items, use the media type specific component
            if (!item)
                return nothing;
            const href = `${this._editPath}edit/${unique}`;
            return html `
							<uui-ref-node-document-type name=${this.localize.string(item.name)} id=${unique}>
								${this.#renderIcon(item)}
								<uui-action-bar slot="actions">
									<uui-button href=${href} label=${this.localize.term('general_open')}></uui-button>
									<uui-button
										label=${this.localize.term('general_remove')}
										@click=${() => this.#removeItem(unique)}></uui-button>
								</uui-action-bar>
							</uui-ref-node-document-type>
						`;
        })}
			</uui-ref-list>
		`;
    }
    #renderIcon(item) {
        if (!item.icon)
            return;
        return html `<umb-icon slot="icon" name=${item.icon}></umb-icon>`;
    }
    static { this.styles = [
        css `
			#btn-add {
				width: 100%;
			}
		`,
    ]; }
};
__decorate([
    property({ type: Number })
], UmbInputMediaTypeElement.prototype, "min", null);
__decorate([
    property({ type: String, attribute: 'min-message' })
], UmbInputMediaTypeElement.prototype, "minMessage", void 0);
__decorate([
    property({ type: Number })
], UmbInputMediaTypeElement.prototype, "max", null);
__decorate([
    property({ type: String, attribute: 'min-message' })
], UmbInputMediaTypeElement.prototype, "maxMessage", void 0);
__decorate([
    property({ type: Array })
], UmbInputMediaTypeElement.prototype, "selection", null);
__decorate([
    property({ type: String })
], UmbInputMediaTypeElement.prototype, "value", null);
__decorate([
    state()
], UmbInputMediaTypeElement.prototype, "_items", void 0);
__decorate([
    state()
], UmbInputMediaTypeElement.prototype, "_statuses", void 0);
__decorate([
    state()
], UmbInputMediaTypeElement.prototype, "_editPath", void 0);
UmbInputMediaTypeElement = __decorate([
    customElement('umb-input-media-type')
], UmbInputMediaTypeElement);
export { UmbInputMediaTypeElement };
export default UmbInputMediaTypeElement;
