import { UmbReadOnlyGuardManager } from './readonly-guard.manager.js';
import { mergeObservables } from '../../../../libs/observable-api/index.js';
/**
 *
 * @param rule
 * @param variantId
 */
function findRule(rule, variantId) {
    return rule.variantId?.compare(variantId) || rule.variantId === undefined;
}
// TODO: Check the need for this one.
/**
 * Read only guard manager for variant rules.
 * @export
 * @class UmbReadOnlyVariantGuardManager
 * @augments {UmbReadOnlyGuardManager<UmbVariantGuardRule>}
 */
export class UmbReadOnlyVariantGuardManager extends UmbReadOnlyGuardManager {
    /**
     * Observe if the given variantId is permitted to read
     * @param {UmbVariantId} variantId
     * @returns {Observable<boolean>} - Observable that emits true if the variantId is permitted to read, false otherwise
     * @memberof UmbReadOnlyVariantGuardManager
     */
    isPermittedForVariant(variantId) {
        return this._rules.asObservablePart((states) => {
            return this.#resolvePermission(states, variantId);
        });
    }
    /**
     * @param {Observable<UmbVariantId | undefined>} variantId
     * @returns {Observable<boolean>} - Observable that emits true if the variantId is permitted to read, false otherwise
     * @memberof UmbReadOnlyVariantGuardManager
     */
    isPermittedForObservableVariant(variantId) {
        return mergeObservables([this.rules, variantId], ([states, variantId]) => {
            if (!variantId) {
                // Or should we know about the fallback state here? [NL]
                return false;
            }
            return this.#resolvePermission(states, variantId);
        });
    }
    /**
     * Check if the given variantId is permitted to read
     * @param {UmbVariantId} variantId
     * @returns {boolean} - true if the variantId is permitted to read, false otherwise
     * @memberof UmbReadOnlyVariantGuardManager
     */
    getIsPermittedForVariant(variantId) {
        return this.#resolvePermission(this.getRules(), variantId);
    }
    #resolvePermission(rules, variantId) {
        if (rules.filter((x) => x.permitted === false).some((rule) => findRule(rule, variantId))) {
            return false;
        }
        if (rules.filter((x) => x.permitted === true).some((rule) => findRule(rule, variantId))) {
            return true;
        }
        return this._fallback;
    }
}
