import { UMB_DOCUMENT_CONFIGURATION_CONTEXT } from '../global-contexts/document-configuration.context.js';
import { UmbControllerBase } from '../../../../libs/class-api/index.js';
import { observeMultiple } from '../../../../libs/observable-api/index.js';
import { UmbVariantId } from '../../../core/variant/index.js';
export class UmbDocumentAllowEditInvariantFromNonDefaultControllerBase extends UmbControllerBase {
    constructor(host) {
        super(host);
        this.consumeContext(UMB_DOCUMENT_CONFIGURATION_CONTEXT, async (context) => {
            const config = await context?.getDocumentConfiguration();
            const allowEditInvariantFromNonDefault = config?.allowEditInvariantFromNonDefault ?? true;
            if (allowEditInvariantFromNonDefault === false) {
                this._preventEditInvariantFromNonDefault();
            }
        });
    }
    _observeAndApplyRule(args) {
        this.observe(observeMultiple([args.propertiesObservable, args.variantOptionsObservable]), ([properties, variantOptions]) => {
            if (properties.length === 0)
                return;
            if (variantOptions.length === 0)
                return;
            variantOptions.forEach((variantOption) => {
                // Do not add a rule for the default language. It is always permitted to edit.
                if (variantOption.language.isDefault)
                    return;
                const datasetVariantId = UmbVariantId.CreateFromPartial(variantOption);
                const rule = this._createRule({ datasetVariantId });
                args.propertyWriteGuard.addRule(rule);
            });
        });
    }
    _createRule(args) {
        // always target invariant properties
        const propertyVariantId = UmbVariantId.CreateInvariant();
        const unique = `UMB_PREVENT_EDIT_INVARIANT_FROM_NON_DEFAULT_DATASET=${args.datasetVariantId.toString()}_PROPERTY_${propertyVariantId.toString()}`;
        const rule = {
            unique,
            message: 'Shared properties can only be edited in the default language',
            variantId: propertyVariantId,
            datasetVariantId: args.datasetVariantId,
            permitted: false,
        };
        return rule;
    }
}
