import { UMB_COLLECTION_MENU_CONTEXT } from './default-collection-menu.context.token.js';
import { UmbContextBase } from '../../../../../libs/class-api/index.js';
import { UmbPaginationManager, UmbSelectionManager } from '../../../utils/index.js';
import { UmbChangeEvent } from '../../../event/index.js';
import { UmbExtensionApiInitializer } from '../../../../../libs/extension-api/index.js';
import { umbExtensionsRegistry } from '../../../extension-registry/index.js';
import { UmbArrayState } from '../../../../../libs/observable-api/index.js';
export class UmbDefaultCollectionMenuContext extends UmbContextBase {
    #items;
    #manifest;
    #repository;
    #paging;
    #initResolver;
    #initialized;
    #init;
    constructor(host) {
        super(host, UMB_COLLECTION_MENU_CONTEXT);
        this.selectableFilter = () => true;
        this.filter = () => true;
        this.selection = new UmbSelectionManager(this);
        this.pagination = new UmbPaginationManager();
        this.#items = new UmbArrayState([], (x) => x.unique);
        this.items = this.#items.asObservable();
        this.#paging = {
            skip: 0,
            take: 50,
        };
        this.#initialized = false;
        this.#init = new Promise((resolve) => {
            if (this.#initialized) {
                resolve();
            }
            else {
                this.#initResolver = resolve;
            }
        });
        this.#onPageChange = (event) => {
            const target = event.target;
            this.#paging.skip = target.getSkip();
            this.#loadItems(true);
        };
        this.pagination.setPageSize(this.#paging.take);
        //this.#consumeContexts();
        // listen for page changes on the pagination manager
        this.pagination.addEventListener(UmbChangeEvent.TYPE, this.#onPageChange);
        // always load the tree root because we need the root entity to reload the entire tree
        this.#loadItems();
    }
    /**
     * Sets the manifest
     * @param {ManifestTree} manifest
     * @memberof UmbDefaultTreeContext
     */
    set manifest(manifest) {
        if (this.#manifest === manifest)
            return;
        this.#manifest = manifest;
        this.#observeRepository(this.#manifest?.meta.collectionRepositoryAlias);
    }
    get manifest() {
        return this.#manifest;
    }
    #checkIfInitialized() {
        if (this.#repository) {
            this.#initialized = true;
            this.#initResolver?.();
        }
    }
    #onPageChange;
    async #loadItems(loadMore = false) {
        await this.#init;
        const skip = loadMore ? this.#paging.skip : 0;
        const take = loadMore ? this.#paging.take : this.pagination.getCurrentPageNumber() * this.#paging.take;
        const { data } = await this.#repository.requestCollection({
            ...this.filterArgs,
            skip,
            take,
        });
        if (data) {
            if (loadMore) {
                const currentItems = this.#items.getValue();
                this.#items.setValue([...currentItems, ...data.items]);
            }
            else {
                this.#items.setValue(data.items);
            }
            this.pagination.setTotalItems(data.total);
        }
    }
    #observeRepository(repositoryAlias) {
        if (!repositoryAlias)
            throw new Error('Collection Menu must have a repository alias.');
        new UmbExtensionApiInitializer(this, umbExtensionsRegistry, repositoryAlias, [this], (permitted, ctrl) => {
            this.#repository = permitted ? ctrl.api : undefined;
            this.#checkIfInitialized();
        });
    }
}
export { UmbDefaultCollectionMenuContext as api };
