import { UMB_MEMBER_ENTITY_TYPE } from '../../entity.js';
import { tryExecute } from '../../../../core/resources/index.js';
import { DirectionModel, MemberService } from '../../../../core/backend-api/index.js';
import { UmbDirection } from '../../../../core/utils/index.js';
/**
 * A data source that fetches the member collection data from the server.
 * @class UmbMemberCollectionServerDataSource
 * @implements {UmbCollectionDataSource}
 */
export class UmbMemberCollectionServerDataSource {
    #host;
    /**
     * Creates an instance of UmbMemberCollectionServerDataSource.
     * @param {UmbControllerHost} host - The controller host for this controller to be appended to
     * @memberof UmbMemberCollectionServerDataSource
     */
    constructor(host) {
        this.#host = host;
    }
    /**
     * Gets the member collection filtered by the given filter.
     * @param {UmbMemberCollectionFilterModel} filter
     * @returns {*}
     * @memberof UmbMemberCollectionServerDataSource
     */
    async getCollection(filter) {
        const query = {
            memberTypeId: filter.memberTypeId,
            filter: filter.filter,
            orderBy: filter.orderBy ?? 'username',
            orderDirection: filter.orderDirection === UmbDirection.DESCENDING ? DirectionModel.DESCENDING : DirectionModel.ASCENDING,
            skip: filter.skip ?? 0,
            take: filter.take ?? 100,
        };
        const { data, error } = await tryExecute(this.#host, MemberService.getFilterMember({ query }));
        if (error) {
            return { error };
        }
        if (!data) {
            return { data: { items: [], total: 0 } };
        }
        const { items, total } = data;
        const mappedItems = items.map((item) => {
            const memberDetail = {
                entityType: UMB_MEMBER_ENTITY_TYPE,
                email: item.email,
                variants: item.variants,
                unique: item.id,
                kind: item.kind,
                lastLoginDate: item.lastLoginDate || null,
                lastLockoutDate: item.lastLockoutDate || null,
                lastPasswordChangeDate: item.lastPasswordChangeDate || null,
                failedPasswordAttempts: item.failedPasswordAttempts,
                isApproved: item.isApproved,
                isLockedOut: item.isLockedOut,
                groups: item.groups,
                isTwoFactorEnabled: item.isTwoFactorEnabled,
                memberType: { unique: item.memberType.id, icon: item.memberType.icon },
                username: item.username,
                values: item.values,
                flags: item.flags,
            };
            return memberDetail;
        });
        return { data: { items: mappedItems, total } };
    }
}
