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 { UMB_CONTENT_PICKER_DOCUMENT_ROOT_ORIGIN_PICKER_MODAL, UMB_CONTENT_PICKER_DOCUMENT_ROOT_QUERY_STEP_PICKER_MODAL, } from '../modals/index.js';
import { css, customElement, html, ifDefined, property, repeat, state } from '../../../../../external/lit/index.js';
import { UmbChangeEvent } from '../../../../core/event/index.js';
import { umbExtensionsRegistry } from '../../../../core/extension-registry/index.js';
import { UmbFormControlMixin } from '../../../../core/validation/index.js';
import { UmbId } from '../../../../core/id/index.js';
import { UmbLitElement } from '../../../../core/lit-element/index.js';
import { UmbRepositoryItemsManager } from '../../../../core/repository/index.js';
import { UmbSorterController } from '../../../../core/sorter/index.js';
import { UMB_DOCUMENT_ITEM_REPOSITORY_ALIAS } from '../../../../documents/documents/index.js';
import { UMB_DOCUMENT_TYPE_ITEM_REPOSITORY_ALIAS } from '../../../../documents/document-types/index.js';
import { UMB_MODAL_MANAGER_CONTEXT } from '../../../../core/modal/index.js';
const elementName = 'umb-input-content-picker-document-root';
let UmbInputContentPickerDocumentRootElement = class UmbInputContentPickerDocumentRootElement extends UmbFormControlMixin(UmbLitElement) {
    #documentItemManager;
    #documentTypeItemManager;
    getFormElement() {
        return undefined;
    }
    #dynamicRootOrigin;
    #documentLookup;
    #documentTypeLookup;
    #modalContext;
    #openModal;
    constructor() {
        super();
        this.#documentItemManager = new UmbRepositoryItemsManager(this, UMB_DOCUMENT_ITEM_REPOSITORY_ALIAS);
        this.#documentTypeItemManager = new UmbRepositoryItemsManager(this, UMB_DOCUMENT_TYPE_ITEM_REPOSITORY_ALIAS);
        this._originManifests = [];
        this._queryStepManifests = [];
        this.#documentLookup = {};
        this.#documentTypeLookup = {};
        this.#sorter = new UmbSorterController(this, {
            getUniqueOfElement: (element) => {
                return element.id;
            },
            getUniqueOfModel: (modelEntry) => {
                return modelEntry.unique;
            },
            identifier: 'Umb.SorterIdentifier.InputDynamicRoot',
            itemSelector: 'uui-ref-node',
            containerSelector: '#query-steps',
            onChange: ({ model }) => {
                if (this.data?.querySteps) {
                    const querySteps = model;
                    this.#updateDynamicRootQuerySteps(querySteps);
                    this.dispatchEvent(new UmbChangeEvent());
                }
            },
        });
        this.consumeContext(UMB_MODAL_MANAGER_CONTEXT, (instance) => {
            this.#modalContext = instance;
        });
        this.observe(umbExtensionsRegistry.byType('dynamicRootOrigin'), (originManifests) => {
            this._originManifests = originManifests;
        });
        this.observe(umbExtensionsRegistry.byType('dynamicRootQueryStep'), (queryStepManifests) => {
            this._queryStepManifests = queryStepManifests;
        });
        this.observe(this.#documentItemManager.items, (documents) => {
            if (!documents?.length)
                return;
            documents.forEach((document) => {
                // TODO: [v17] Review usage of `item.variants[0].name` as this needs to be implemented properly! [LK]
                this.#documentLookup[document.unique] = document.variants[0].name;
            });
            this.requestUpdate();
        });
        this.observe(this.#documentTypeItemManager.items, (documentTypes) => {
            if (!documentTypes?.length)
                return;
            documentTypes.forEach((documentType) => {
                this.#documentTypeLookup[documentType.unique] = documentType.name;
            });
            this.requestUpdate();
        });
    }
    connectedCallback() {
        super.connectedCallback();
        this.#updateDynamicRootOrigin(this.data);
        this.#updateDynamicRootQuerySteps(this.data?.querySteps);
    }
    #sorter;
    #openDynamicRootOriginPicker() {
        this.#openModal = this.#modalContext?.open(this, UMB_CONTENT_PICKER_DOCUMENT_ROOT_ORIGIN_PICKER_MODAL, {
            data: { items: this._originManifests },
        });
        this.#openModal?.onSubmit().then((data) => {
            const existingData = { ...this.data };
            existingData.originKey = undefined;
            this.data = { ...existingData, ...data };
            this.#updateDynamicRootOrigin(this.data);
            this.dispatchEvent(new UmbChangeEvent());
        });
    }
    #openDynamicRootQueryStepPicker() {
        this.#openModal = this.#modalContext?.open(this, UMB_CONTENT_PICKER_DOCUMENT_ROOT_QUERY_STEP_PICKER_MODAL, {
            data: { items: this._queryStepManifests },
        });
        this.#openModal?.onSubmit().then((step) => {
            if (this.data) {
                const querySteps = [...(this.data.querySteps ?? []), step];
                this.#updateDynamicRootQuerySteps(querySteps);
                this.dispatchEvent(new UmbChangeEvent());
            }
        });
    }
    #updateDynamicRootOrigin(data) {
        if (!data)
            return;
        const origin = this._originManifests.find((item) => item.meta.originAlias === data.originAlias)?.meta;
        if (data.originKey) {
            this.#documentItemManager.setUniques([data.originKey]);
        }
        this.#dynamicRootOrigin = {
            label: origin?.label ?? data.originAlias,
            icon: origin?.icon ?? 'icon-wand',
            description: data.originKey,
        };
    }
    #updateDynamicRootQuerySteps(querySteps) {
        if (!this.data)
            return;
        if (querySteps) {
            // NOTE: Ensure that the `unique` ID is populated for each query step. [LK]
            querySteps = querySteps.map((item) => (item.unique ? item : { ...item, unique: UmbId.new() }));
        }
        this.#documentTypeItemManager.setUniques((querySteps ?? []).map((x) => x.anyOfDocTypeKeys ?? []).flat());
        this.#sorter?.setModel(querySteps ?? []);
        this.data = { ...this.data, ...{ querySteps } };
    }
    #getQueryStepMeta(item) {
        const step = this._queryStepManifests.find((step) => step.meta.queryStepAlias === item.alias)?.meta;
        const docTypeNames = item.anyOfDocTypeKeys
            ?.map((docTypeKey) => this.#documentTypeLookup[docTypeKey] ?? docTypeKey)
            .sort()
            .join(', ') ?? '';
        const description = item.anyOfDocTypeKeys
            ? this.localize.term('dynamicRoot_queryStepTypes') + docTypeNames
            : undefined;
        return {
            unique: item.unique,
            label: step?.label ?? item.alias,
            icon: step?.icon ?? 'icon-lab',
            description,
        };
    }
    #removeDynamicRootQueryStep(item) {
        if (this.data?.querySteps) {
            const index = this.data.querySteps.indexOf(item);
            if (index !== -1) {
                const querySteps = [...this.data.querySteps];
                querySteps.splice(index, 1);
                this.#updateDynamicRootQuerySteps(querySteps);
                this.dispatchEvent(new UmbChangeEvent());
            }
        }
    }
    #clearDynamicRootQuery() {
        this.data = undefined;
        this.#dynamicRootOrigin = undefined;
        this.dispatchEvent(new UmbChangeEvent());
    }
    render() {
        return html `
			${this.#renderAddOriginButton()}
			<uui-ref-list>${this.#renderOrigin()}</uui-ref-list>
			<uui-ref-list id="query-steps">${this.#renderQuerySteps()}</uui-ref-list>
			${this.#renderAddQueryStepButton()} ${this.#renderClearButton()}
		`;
    }
    #renderAddOriginButton() {
        if (this.data?.originAlias)
            return;
        return html `
			<uui-button
				class="add-button"
				@click=${this.#openDynamicRootOriginPicker}
				label=${this.localize.term('contentPicker_defineDynamicRoot')}
				look="placeholder"></uui-button>
		`;
    }
    #renderOrigin() {
        if (!this.#dynamicRootOrigin)
            return;
        const description = this.#dynamicRootOrigin.description
            ? this.#documentLookup[this.#dynamicRootOrigin.description]
            : '';
        return html `
			<uui-ref-node standalone name=${this.#dynamicRootOrigin.label} detail=${ifDefined(description)}>
				<umb-icon slot="icon" name=${ifDefined(this.#dynamicRootOrigin.icon)}></umb-icon>
				<uui-action-bar slot="actions">
					<uui-button
						@click=${this.#openDynamicRootOriginPicker}
						label="${this.localize.term('general_edit')}"></uui-button>
				</uui-action-bar>
			</uui-ref-node>
		`;
    }
    #renderClearButton() {
        if (!this.#dynamicRootOrigin)
            return;
        return html `
			<uui-button @click=${this.#clearDynamicRootQuery}>${this.localize.term('buttons_clearSelection')}</uui-button>
		`;
    }
    #renderQuerySteps() {
        if (!this.data?.querySteps)
            return;
        return repeat(this.data.querySteps, (item) => item.unique, (item) => this.#renderQueryStep(item));
    }
    #renderQueryStep(item) {
        if (!item.alias)
            return;
        const step = this.#getQueryStepMeta(item);
        return html `
			<uui-ref-node standalone id=${step.unique} name=${step.label} detail="${ifDefined(step.description)}">
				<umb-icon slot="icon" name=${step.icon}></umb-icon>
				<uui-action-bar slot="actions">
					<uui-button
						@click=${() => this.#removeDynamicRootQueryStep(item)}
						label=${this.localize.term('general_remove')}></uui-button>
				</uui-action-bar>
			</uui-ref-node>
		`;
    }
    #renderAddQueryStepButton() {
        if (!this.#dynamicRootOrigin)
            return;
        return html ` <uui-button
			class="add-button"
			@click=${this.#openDynamicRootQueryStepPicker}
			label=${this.localize.term('dynamicRoot_addQueryStep')}
			look="placeholder"></uui-button>`;
    }
    static { this.styles = [
        css `
			.add-button {
				width: 100%;
			}

			uui-ref-node[drag-placeholder] {
				opacity: 0.2;
			}
		`,
    ]; }
};
__decorate([
    state()
], UmbInputContentPickerDocumentRootElement.prototype, "_originManifests", void 0);
__decorate([
    state()
], UmbInputContentPickerDocumentRootElement.prototype, "_queryStepManifests", void 0);
__decorate([
    property({ attribute: false })
], UmbInputContentPickerDocumentRootElement.prototype, "data", void 0);
UmbInputContentPickerDocumentRootElement = __decorate([
    customElement(elementName)
], UmbInputContentPickerDocumentRootElement);
export { UmbInputContentPickerDocumentRootElement };
export { UmbInputContentPickerDocumentRootElement as element };
