import { tryExecute } from '../../resources/index.js';
import { UmbControllerBase } from '../../../../libs/class-api/index.js';
/**
 * A data source for a tree that fetches data from the server
 * @class UmbTreeServerDataSourceBase
 * @implements {UmbTreeDataSource}
 */
export class UmbTreeServerDataSourceBase extends UmbControllerBase {
    #getRootItems;
    #getChildrenOf;
    #getAncestorsOf;
    #mapper;
    /**
     * Creates an instance of UmbTreeServerDataSourceBase.
     * @param {UmbControllerHost} host - The controller host for this controller to be appended to
     * @param args
     * @memberof UmbTreeServerDataSourceBase
     */
    constructor(host, args) {
        super(host);
        this.#getRootItems = args.getRootItems;
        this.#getChildrenOf = args.getChildrenOf;
        this.#getAncestorsOf = args.getAncestorsOf;
        this.#mapper = args.mapper;
    }
    /**
     * Fetches the root items for the tree from the server
     * @param {UmbTreeRootItemsRequestArgs} args
     * @returns {*}
     * @memberof UmbTreeServerDataSourceBase
     */
    async getRootItems(args) {
        const { data, error } = await tryExecute(this, this.#getRootItems(args));
        if (data) {
            const items = data?.items.map((item) => this.#mapper(item));
            return {
                data: {
                    total: data.total,
                    totalBefore: data.totalBefore,
                    totalAfter: data.totalAfter,
                    items,
                },
            };
        }
        return { error };
    }
    /**
     * Fetches the children of a given parent unique from the server
     * @param {UmbTreeChildrenOfRequestArgs} args
     * @returns {*}
     * @memberof UmbTreeServerDataSourceBase
     */
    async getChildrenOf(args) {
        if (args.parent.unique === undefined)
            throw new Error('Parent unique is missing');
        const { data, error } = await tryExecute(this, this.#getChildrenOf(args));
        if (data) {
            const items = data?.items.map((item) => this.#mapper(item));
            return {
                data: {
                    total: data.total,
                    totalBefore: data.totalBefore,
                    totalAfter: data.totalAfter,
                    items,
                },
            };
        }
        return { error };
    }
    /**
     * Fetches the ancestors of a given item from the server
     * @param {UmbTreeAncestorsOfRequestArgs} args
     * @returns {*}
     * @memberof UmbTreeServerDataSourceBase
     */
    async getAncestorsOf(args) {
        if (!args.treeItem.entityType)
            throw new Error('Parent unique is missing');
        const { data, error } = await tryExecute(this, this.#getAncestorsOf(args));
        if (data) {
            const items = data?.map((item) => this.#mapper(item));
            return { data: items };
        }
        return { error };
    }
}
