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 { html, customElement, css, state, nothing } from '../../../../../../external/lit/index.js';
import { UmbTextStyles } from '../../../../style/index.js';
import { UmbModalBaseElement } from '../../../../modal/index.js';
import { createExtensionApiByAlias } from '../../../../extension-registry/index.js';
import { UmbPaginationManager } from '../../../../utils/index.js';
import { observeMultiple } from '../../../../../../libs/observable-api/index.js';
const elementName = 'umb-sort-children-of-modal';
let UmbSortChildrenOfModalElement = class UmbSortChildrenOfModalElement extends UmbModalBaseElement {
    #pagination;
    constructor() {
        super();
        this._children = [];
        this._currentPage = 1;
        this._totalPages = 1;
        this._tableColumns = [];
        this._tableConfig = {
            allowSelection: false,
        };
        this._tableItems = [];
        this._sortable = false;
        this._sortedUniques = new Set();
        this.#pagination = new UmbPaginationManager();
        this.#pagination.setPageSize(50);
        this.observe(observeMultiple([this.#pagination.currentPage, this.#pagination.totalPages]), ([currentPage, totalPages]) => {
            this._currentPage = currentPage;
            this._totalPages = totalPages;
        }, 'umbPaginationObserver');
    }
    _setTableColumns() {
        this._tableColumns = [
            {
                name: this.localize.term('general_name'),
                alias: 'name',
                allowSorting: true,
            },
        ];
    }
    async firstUpdated(_changedProperties) {
        super.firstUpdated(_changedProperties);
        await this.#requestChildren();
        this._setTableColumns();
    }
    async #requestChildren() {
        if (this.data?.unique === undefined)
            throw new Error('unique is required');
        if (!this.data?.treeRepositoryAlias)
            throw new Error('treeRepositoryAlias is required');
        const treeRepository = await createExtensionApiByAlias(this, this.data.treeRepositoryAlias);
        const { data } = await treeRepository.requestTreeItemsOf({
            parent: {
                unique: this.data.unique,
                entityType: this.data.entityType,
            },
            skip: this.#pagination.getSkip(),
            take: this.#pagination.getPageSize(),
        });
        if (data) {
            this._children = [...this._children, ...data.items];
            this.#pagination.setTotalItems(data.total);
            this._sortable = this._children.length > 0;
            this._createTableItems();
        }
    }
    _createTableItems() {
        this._tableItems = this._children.map((treeItem) => {
            return {
                id: treeItem.unique,
                icon: 'icon-globe',
                data: [
                    {
                        columnAlias: 'name',
                        value: html `${treeItem.name}`,
                    },
                ],
            };
        });
    }
    _hasMorePages() {
        return this._currentPage < this._totalPages;
    }
    _onLoadMore(event) {
        event.stopPropagation();
        if (this._currentPage >= this._totalPages)
            return;
        this.#pagination.setCurrentPageNumber(this._currentPage + 1);
        this.#requestChildren();
    }
    async #onSubmit(event) {
        event?.stopPropagation();
        if (!this.data?.sortChildrenOfRepositoryAlias)
            throw new Error('sortChildrenOfRepositoryAlias is required');
        const sortChildrenOfRepository = await createExtensionApiByAlias(this, this.data.sortChildrenOfRepositoryAlias);
        const { error } = await sortChildrenOfRepository.sortChildrenOf({
            unique: this.data.unique,
            sorting: this.#getSortOrderOfSortedItems(),
        });
        if (!error) {
            this._submitModal();
        }
    }
    #getSortOrderOfSortedItems() {
        const sorting = [];
        // get the new sort order from the sorted uniques
        for (const value of this._sortedUniques) {
            const index = this._tableItems.findIndex((tableItem) => tableItem.id === value);
            if (index !== -1) {
                const entry = {
                    unique: value,
                    sortOrder: index,
                };
                sorting.push(entry);
            }
        }
        return sorting;
    }
    #onSorted(event) {
        event.stopPropagation();
        const sortedId = event.getItemId();
        this._sortedUniques.add(sortedId);
        const target = event.target;
        const items = target.items;
        this._tableItems = items;
    }
    #onOrdered(event) {
        event.stopPropagation();
        const target = event.target;
        const orderingColumn = target.orderingColumn;
        const orderingDesc = target.orderingDesc;
        this._tableItems = [...this._tableItems].sort((a, b) => {
            const aColumn = a.data.find((column) => column.columnAlias === orderingColumn);
            const bColumn = b.data.find((column) => column.columnAlias === orderingColumn);
            return this._sortCompare(orderingColumn, aColumn?.value, bColumn?.value);
        });
        if (orderingDesc) {
            this._tableItems.reverse();
        }
        this._sortedUniques.clear();
        this._tableItems.map((tableItem) => tableItem.id).forEach((u) => this._sortedUniques.add(u));
    }
    _sortCompare(columnAlias, valueA, valueB) {
        if (columnAlias === 'name') {
            return valueA.localeCompare(valueB);
        }
        return 0;
    }
    render() {
        return html `
			<umb-body-layout headline=${'Sort Children'}>
				${this._children.length === 0 ? this.#renderEmptyState() : this.#renderTable()}
				<uui-button slot="actions" label="Cancel" @click="${this._rejectModal}"></uui-button>
				<uui-button slot="actions" color="positive" look="primary" label="Sort" @click=${this.#onSubmit}></uui-button>
			</umb-body-layout>
		`;
    }
    #renderEmptyState() {
        return html `<uui-label>There are no children</uui-label>`;
    }
    #renderTable() {
        return html `
			<umb-table
				.config=${this._tableConfig}
				.columns=${this._tableColumns}
				.items=${this._tableItems}
				.sortable=${this._sortable}
				@sorted=${this.#onSorted}
				@ordered=${this.#onOrdered}></umb-table>

			${this._hasMorePages()
            ? html `
						<uui-button id="loadMoreButton" look="placeholder" @click=${this._onLoadMore}
							>Load more (${this._currentPage}/${this._totalPages})</uui-button
						>
					`
            : nothing}
		`;
    }
    static { this.styles = [
        UmbTextStyles,
        css `
			#loadMoreButton {
				width: 100%;
				margin-top: var(--uui-size-space-3);
			}
		`,
    ]; }
};
__decorate([
    state()
], UmbSortChildrenOfModalElement.prototype, "_children", void 0);
__decorate([
    state()
], UmbSortChildrenOfModalElement.prototype, "_currentPage", void 0);
__decorate([
    state()
], UmbSortChildrenOfModalElement.prototype, "_totalPages", void 0);
__decorate([
    state()
], UmbSortChildrenOfModalElement.prototype, "_tableColumns", void 0);
__decorate([
    state()
], UmbSortChildrenOfModalElement.prototype, "_tableConfig", void 0);
__decorate([
    state()
], UmbSortChildrenOfModalElement.prototype, "_tableItems", void 0);
__decorate([
    state()
], UmbSortChildrenOfModalElement.prototype, "_sortable", void 0);
UmbSortChildrenOfModalElement = __decorate([
    customElement(elementName)
], UmbSortChildrenOfModalElement);
export { UmbSortChildrenOfModalElement };
export { UmbSortChildrenOfModalElement as element };
