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 { UmbClipboardCollectionRepository } from '../../collection/index.js';
import UmbClipboardEntryDetailRepository from '../detail/clipboard-entry-detail.repository.js';
import { css, customElement, html, nothing, property, repeat, state, when } from '../../../../external/lit/index.js';
import { UmbEntityContext } from '../../../core/entity/index.js';
import { UmbLitElement } from '../../../core/lit-element/index.js';
import { UmbRequestReloadChildrenOfEntityEvent, UmbRequestReloadStructureForEntityEvent, } from '../../../core/entity-action/index.js';
import { UmbSelectionManager } from '../../../core/utils/index.js';
import { UMB_ACTION_EVENT_CONTEXT } from '../../../core/action/index.js';
import { umbConfirmModal } from '../../../core/modal/index.js';
// TODO: make this into an extension point (Picker) with two kinds of pickers: tree-item-picker and collection-item-picker;
let UmbClipboardEntryPickerElement = class UmbClipboardEntryPickerElement extends UmbLitElement {
    #collectionRepository;
    #selectionManager;
    #entityContext;
    #actionEventContext;
    #clipboardDetailRepository;
    constructor() {
        super();
        this.selection = [];
        this._items = [];
        this.#collectionRepository = new UmbClipboardCollectionRepository(this);
        this.#selectionManager = new UmbSelectionManager(this);
        this.#entityContext = new UmbEntityContext(this);
        this.#clipboardDetailRepository = new UmbClipboardEntryDetailRepository(this);
        this.#onReloadStructureRequest = (event) => {
            const hasItem = this._items.some((item) => item.unique === event.getUnique());
            if (hasItem) {
                this.#requestItems();
            }
        };
        this.#onReloadChildrenRequest = async (event) => {
            // check if the collection is in the same context as the entity from the event
            const unique = this.#entityContext.getUnique();
            const entityType = this.#entityContext.getEntityType();
            if (unique === event.getUnique() && entityType === event.getEntityType()) {
                this.#requestItems();
            }
        };
        this.#entityContext.setEntityType('clipboard-entry');
        this.#entityContext.setUnique(null);
    }
    connectedCallback() {
        super.connectedCallback();
        this.#selectionManager.setSelectable(true);
        this.#selectionManager.setMultiple(this.config?.multiple ?? false);
        this.#selectionManager.setSelection(this.selection ?? []);
        this.observe(this.#selectionManager.selection, (selection) => {
            this.selection = selection;
        });
        this.#listenToEntityEvents();
    }
    async firstUpdated() {
        this.#requestItems();
    }
    async #requestItems() {
        const { data } = await this.#collectionRepository.requestCollection({
            types: this.config?.entryTypes ?? [],
        });
        const entries = data?.items ?? [];
        const sortedEntries = entries.sort((a, b) => new Date(b.updateDate).getTime() - new Date(a.updateDate).getTime());
        if (this.config?.filter) {
            this._items = sortedEntries.filter(this.config.filter);
            return;
        }
        if (this.config?.asyncFilter) {
            const promises = Promise.all(sortedEntries.map(this.config.asyncFilter));
            const results = await promises;
            this._items = sortedEntries.filter((_, index) => results[index]);
            return;
        }
        this._items = sortedEntries;
    }
    async #listenToEntityEvents() {
        this.consumeContext(UMB_ACTION_EVENT_CONTEXT, (context) => {
            this.#actionEventContext = context;
            context?.removeEventListener(UmbRequestReloadStructureForEntityEvent.TYPE, this.#onReloadStructureRequest);
            context?.removeEventListener(UmbRequestReloadChildrenOfEntityEvent.TYPE, this.#onReloadChildrenRequest);
            context?.addEventListener(UmbRequestReloadStructureForEntityEvent.TYPE, this.#onReloadStructureRequest);
            context?.addEventListener(UmbRequestReloadChildrenOfEntityEvent.TYPE, this.#onReloadChildrenRequest);
        });
    }
    #onReloadStructureRequest;
    #onReloadChildrenRequest;
    async #clearClipboard() {
        try {
            await umbConfirmModal(this, {
                headline: '#clipboard_labelForClearClipboard',
                content: '#clipboard_confirmClearDescription',
                color: 'danger',
                confirmLabel: '#general_clear',
                cancelLabel: '#general_cancel',
            });
        }
        catch {
            return;
        }
        for (const item of this._items) {
            const { error } = await this.#clipboardDetailRepository.delete(item.unique);
            if (error) {
                console.error(`Unable to delete clipboard item with unique ${item.unique}`, error);
            }
        }
        this.#requestItems();
    }
    render() {
        return html `
			<uui-box headline=${this.localize.term('general_clipboard')}>
				<span slot="header-actions">
					${when(this._items.length > 0, () => html `
							<uui-button color="default" look="default" @click="${this.#clearClipboard}">
								<uui-icon name="delete"></uui-icon>
								<umb-localize key="clipboard_labelForClearClipboard">Clear Clipboard</umb-localize>
							</uui-button>
						`, () => nothing)}
				</span>

				${when(this._items.length > 0, () => repeat(this._items, (item) => item.unique, (item) => this.#renderItem(item)), () => html `<p>There are no items in the clipboard.</p>`)}
			</uui-box>
		`;
    }
    #renderItem(item) {
        const label = item.name ?? item.unique;
        return html `
			<uui-menu-item
				label=${label}
				title=${label}
				selectable
				@selected=${() => this.#selectionManager.select(item.unique)}
				@deselected=${() => this.#selectionManager.deselect(item.unique)}
				?selected=${this.selection.includes(item.unique)}>
				${this.#renderItemIcon(item)} ${this.#renderItemActions(item)}
			</uui-menu-item>
		`;
    }
    #renderItemIcon(item) {
        const iconName = item.icon ?? 'icon-clipboard-entry';
        return html `<umb-icon slot="icon" name=${iconName}></umb-icon>`;
    }
    #renderItemActions(item) {
        return html `
			<umb-entity-actions-bundle
				slot="actions"
				.entityType=${item.entityType}
				.unique=${item.unique}
				.label=${this.localize.string(item.name ?? '')}>
			</umb-entity-actions-bundle>
		`;
    }
    destroy() {
        this.#actionEventContext?.removeEventListener(UmbRequestReloadStructureForEntityEvent.TYPE, this.#onReloadStructureRequest);
        this.#actionEventContext?.removeEventListener(UmbRequestReloadChildrenOfEntityEvent.TYPE, this.#onReloadChildrenRequest);
        super.destroy();
    }
    static { this.styles = [
        css `
			:host {
				--uui-menu-item-flat-structure: 1;
			}
		`,
    ]; }
};
__decorate([
    property({ type: Array })
], UmbClipboardEntryPickerElement.prototype, "selection", void 0);
__decorate([
    property({ type: Object })
], UmbClipboardEntryPickerElement.prototype, "config", void 0);
__decorate([
    state()
], UmbClipboardEntryPickerElement.prototype, "_items", void 0);
UmbClipboardEntryPickerElement = __decorate([
    customElement('umb-clipboard-entry-picker')
], UmbClipboardEntryPickerElement);
export { UmbClipboardEntryPickerElement };
