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 { UmbTextStyles } from '../../../../core/style/index.js';
import { html, customElement, state } from '../../../../../external/lit/index.js';
import { UmbLitElement } from '../../../../core/lit-element/index.js';
import { createExtensionApiByAlias } from '../../../../core/extension-registry/index.js';
import { UMB_COLLECTION_CONTEXT } from '../../../../core/collection/index.js';
import '../components/user-group-table-name-column-layout.element.js';
import '../components/user-group-table-sections-column-layout.element.js';
let UmbUserGroupCollectionTableViewElement = class UmbUserGroupCollectionTableViewElement extends UmbLitElement {
    #collectionContext;
    // TODO: hardcoded dependencies on document and media modules. We should figure out how these dependencies can be added through extensions.
    #documentItemRepository;
    #mediaItemRepository;
    #documentStartNodeMap;
    #mediaStartNodeMap;
    constructor() {
        super();
        this._tableConfig = {
            allowSelection: true,
        };
        this._tableColumns = [
            {
                name: this.localize.term('general_name'),
                alias: 'userGroupName',
                elementName: 'umb-user-group-table-name-column-layout',
            },
            {
                name: this.localize.term('general_description'),
                alias: 'description',
            },
            {
                name: this.localize.term('main_sections'),
                alias: 'userGroupSections',
                elementName: 'umb-user-group-table-sections-column-layout',
            },
            {
                name: this.localize.term('user_startnode'),
                alias: 'userGroupContentStartNode',
            },
            {
                name: this.localize.term('user_mediastartnode'),
                alias: 'userGroupMediaStartNode',
            },
            {
                name: '',
                alias: 'entityActions',
                align: 'right',
            },
        ];
        this._tableItems = [];
        this._selection = [];
        this.#documentStartNodeMap = new Map();
        this.#mediaStartNodeMap = new Map();
        this.consumeContext(UMB_COLLECTION_CONTEXT, (instance) => {
            this.#collectionContext = instance;
            this.observe(this.#collectionContext?.selection.selection, (selection) => (this._selection = selection?.filter((x) => x !== undefined && x !== null) ?? []), 'umbCollectionSelectionObserver');
            this.observe(this.#collectionContext?.items, async (items) => {
                await this.#initRepositories();
                this._createTableItems(items ?? []);
            }, 'umbCollectionItemsObserver');
        });
    }
    async #initRepositories() {
        if (this.#documentItemRepository && this.#mediaItemRepository)
            return;
        // TODO: get back to this when documents have been decoupled from users.
        // The repository alias is hardcoded on purpose to avoid a document import in the user module.
        this.#documentItemRepository = await createExtensionApiByAlias(this, 'Umb.Repository.DocumentItem');
        // TODO: get back to this when media have been decoupled from users.
        // The repository alias is hardcoded on purpose to avoid a media import in the user module.
        this.#mediaItemRepository = await createExtensionApiByAlias(this, 'Umb.Repository.MediaItem');
    }
    async _createTableItems(userGroups) {
        if (!this.#documentItemRepository || !this.#mediaItemRepository) {
            throw new Error('Document and media item repositories are not initialized.');
        }
        await Promise.all([
            this.#requestAndCacheStartNodes(userGroups, 'documentStartNode', this.#documentItemRepository, this.#documentStartNodeMap),
            this.#requestAndCacheStartNodes(userGroups, 'mediaStartNode', this.#mediaItemRepository, this.#mediaStartNodeMap),
        ]);
        this._tableItems = userGroups.map((userGroup) => {
            return {
                id: userGroup.unique,
                icon: userGroup.icon,
                data: [
                    {
                        columnAlias: 'userGroupName',
                        value: {
                            name: userGroup.name,
                        },
                    },
                    {
                        columnAlias: 'description',
                        value: userGroup.description ?? '',
                    },
                    {
                        columnAlias: 'userGroupSections',
                        value: userGroup.sections,
                    },
                    {
                        columnAlias: 'userGroupContentStartNode',
                        value: userGroup.documentStartNode
                            ? this.#documentStartNodeMap.get(userGroup.documentStartNode.unique)
                            : this.localize.term('content_contentRoot'),
                    },
                    {
                        columnAlias: 'userGroupMediaStartNode',
                        value: userGroup.mediaStartNode?.unique
                            ? this.#mediaStartNodeMap.get(userGroup.mediaStartNode.unique)
                            : this.localize.term('media_mediaRoot'),
                    },
                    {
                        columnAlias: 'entityActions',
                        value: html `<umb-entity-actions-table-column-view
							.value=${{
                            entityType: userGroup.entityType,
                            unique: userGroup.unique,
                            name: userGroup.name,
                        }}></umb-entity-actions-table-column-view>`,
                    },
                ],
            };
        });
    }
    async #requestAndCacheStartNodes(userGroups, startNodeField, itemRepository, map) {
        const allStartNodes = userGroups.map((userGroup) => userGroup[startNodeField]?.unique).filter(Boolean);
        const uniqueStartNodes = [...new Set(allStartNodes)];
        const uncachedStartNodes = uniqueStartNodes.filter((unique) => !map.has(unique));
        // If there are no uncached start nodes, we don't need to make a request
        if (uncachedStartNodes.length === 0)
            return;
        const { data: items } = await itemRepository.requestItems(uncachedStartNodes);
        if (items) {
            items.forEach((item) => {
                // cache the start node
                map.set(item.unique, item.name);
            });
        }
    }
    #onSelected(event) {
        event.stopPropagation();
        const table = event.target;
        const selection = table.selection;
        this.#collectionContext?.selection.setSelection(selection);
    }
    #onDeselected(event) {
        event.stopPropagation();
        const table = event.target;
        const selection = table.selection;
        this.#collectionContext?.selection.setSelection(selection);
    }
    render() {
        return html `
			<umb-table
				.config=${this._tableConfig}
				.columns=${this._tableColumns}
				.items=${this._tableItems}
				.selection=${this._selection}
				@selected=${this.#onSelected}
				@deselected=${this.#onDeselected}></umb-table>
		`;
    }
    static { this.styles = [UmbTextStyles]; }
};
__decorate([
    state()
], UmbUserGroupCollectionTableViewElement.prototype, "_tableConfig", void 0);
__decorate([
    state()
], UmbUserGroupCollectionTableViewElement.prototype, "_tableColumns", void 0);
__decorate([
    state()
], UmbUserGroupCollectionTableViewElement.prototype, "_tableItems", void 0);
__decorate([
    state()
], UmbUserGroupCollectionTableViewElement.prototype, "_selection", void 0);
UmbUserGroupCollectionTableViewElement = __decorate([
    customElement('umb-user-group-collection-table-view')
], UmbUserGroupCollectionTableViewElement);
export { UmbUserGroupCollectionTableViewElement };
export default UmbUserGroupCollectionTableViewElement;
