/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { Lazy } from "@fluidframework/core-utils/internal";
import { UsageError } from "@fluidframework/telemetry-utils/internal";
import { brand, compareSets, } from "../util/index.js";
import { AnnotatedAllowedTypesInternal, normalizeAllowedTypes } from "./core/index.js";
/**
 * Kind of a field on an {@link TreeObjectNode}.
 * @remarks
 * More kinds may be added over time, so do not assume this is an exhaustive set.
 * See {@link FieldSchema} for where these are used, and {@link SchemaFactory} for how to create schema which use them.
 * @public
 */
export var FieldKind;
(function (FieldKind) {
    /**
     * A field which can be empty or filled.
     * @remarks
     * Allows 0 or one child.
     */
    FieldKind[FieldKind["Optional"] = 0] = "Optional";
    /**
     * A field which must always be filled.
     * @remarks
     * Only allows exactly one child.
     */
    FieldKind[FieldKind["Required"] = 1] = "Required";
    /**
     * A special readonly field used for node identifier strings.
     * @remarks
     * Only allows exactly one child.
     *
     * See {@link SchemaFactory.identifier} for more details.
     */
    FieldKind[FieldKind["Identifier"] = 2] = "Identifier";
})(FieldKind || (FieldKind = {}));
/**
 * Maps from a property key to its corresponding {@link FieldProps.key | stored key} for the provided
 * {@link ImplicitFieldSchema | field schema}.
 *
 * @remarks
 * If an explicit stored key was specified in the schema, it will be used.
 * Otherwise, the stored key is the same as the property key.
 */
export function getStoredKey(propertyKey, fieldSchema) {
    return brand(getExplicitStoredKey(fieldSchema) ?? propertyKey);
}
/**
 * Gets the {@link FieldProps.key | stored key} specified by the schema, if one was explicitly specified.
 * Otherwise, returns undefined.
 */
export function getExplicitStoredKey(fieldSchema) {
    return fieldSchema instanceof FieldSchema ? fieldSchema.props?.key : undefined;
}
/**
 * Returns true if the given {@link FieldProvider} is a {@link ConstantFieldProvider}
 */
export function isConstant(fieldProvider) {
    return fieldProvider.length === 0;
}
export function extractFieldProvider(input) {
    return input;
}
export function getDefaultProvider(input) {
    return input;
}
export function createFieldSchema(kind, annotatedTypes, props) {
    return createFieldSchemaPrivate(kind, annotatedTypes, props);
}
/**
 * Implementation for {@link createFieldSchema}
 */
let createFieldSchemaPrivate;
/**
 * All policy for a specific field,
 * including functionality that does not have to be kept consistent across versions or deterministic.
 *
 * This can include policy for how to use this schema for "view" purposes, and well as how to expose editing APIs.
 * Use {@link SchemaFactory} to create the FieldSchema instances, for example {@link SchemaStatics.optional}.
 * @privateRemarks
 * Public access to the constructor is removed to prevent creating expressible but unsupported (or not stable) configurations.
 * {@link createFieldSchema} can be used internally to create instances.
 *
 * @typeParam TCustomMetadata - Custom metadata properties to associate with the field.
 * See {@link FieldSchemaMetadata.custom}.
 *
 * @remarks
 * All implementations of this are actually {@link FieldSchemaAlpha} which exposes some additional alpha APIs.
 *
 * @sealed @public
 */
export class FieldSchema {
    /**
     * What types of tree nodes are allowed in this field.
     * @remarks Counterpart to {@link FieldSchema.allowedTypes}, with any lazy definitions evaluated.
     */
    get allowedTypeSet() {
        return this.lazyTypes.value;
    }
    /**
     * {@inheritDoc FieldProps.metadata}
     */
    get metadata() {
        return this.props?.metadata ?? {};
    }
    /**
     * This class is `@sealed`: protected members like this constructor are for internal use only.
     * Use {@link SchemaFactory} to create the FieldSchema instances.
     */
    constructor(
    /**
     * The {@link https://en.wikipedia.org/wiki/Kind_(type_theory) | kind } of this field.
     * Determines the multiplicity, viewing and editing APIs as well as the merge resolution policy.
     */
    kind, 
    /**
     * What types of tree nodes are allowed in this field.
     */
    allowedTypes, 
    /**
     * Optional properties associated with the field.
     */
    props) {
        this.kind = kind;
        this.allowedTypes = allowedTypes;
        this.props = props;
        if (!(this instanceof FieldSchemaAlpha)) {
            throw new UsageError("FieldSchema is @sealed: sub-classing is not allowed.");
        }
        this.lazyTypes = new Lazy(() => normalizeAllowedTypes(this.allowedTypes).evaluateSet());
        // TODO: optional fields should (by default) get a default provider that returns undefined, removing the need to special case them here:
        this.requiresValue =
            this.props?.defaultProvider === undefined && this.kind !== FieldKind.Optional;
    }
}
/**
 * {@link FieldSchema} including alpha APIs (currently {@link SimpleFieldSchema}).
 * @remarks
 * This class will go away once the alpha APIs are stable and implemented by {@link FieldSchema}.
 * @sealed @alpha
 */
export class FieldSchemaAlpha extends FieldSchema {
    get persistedMetadata() {
        return this.propsAlpha?.persistedMetadata;
    }
    get isStagedOptional() {
        return this.propsAlpha?.stagedOptionalUpgrade ?? false;
    }
    get allowedTypesIdentifiers() {
        return this.allowedTypesFull.evaluateIdentifiers();
    }
    get simpleAllowedTypes() {
        return AnnotatedAllowedTypesInternal.evaluateSimpleAllowedTypes(this.allowedTypesFull);
    }
    constructor(kind, types, props) {
        super(kind, types, props);
        const normalizedTypes = normalizeAllowedTypes(types);
        this.allowedTypesFull = normalizedTypes;
        this.propsAlpha = props;
    }
}
(() => {
    createFieldSchemaPrivate = (kind, annotatedAllowedTypes, props) => 
    // TCustomMetadata2 requires type assertion due to limitations with dependent type parameters
    new FieldSchemaAlpha(kind, annotatedAllowedTypes, props);
})();
/**
 * Normalizes a {@link ImplicitFieldSchema} or {@link ImplicitFieldSchema} to a {@link FieldSchema}.
 * @internal
 */
export function normalizeFieldSchema(schema) {
    return schema instanceof FieldSchema
        ? schema
        : createFieldSchema(FieldKind.Required, schema);
}
/**
 * Returns true if the given {@link ImplicitFieldSchema} are equivalent, otherwise false.
 * @remarks Two ImplicitFieldSchema are considered equivalent if all of the following are true:
 * 1. They have the same {@link FieldKind | kinds}.
 * 2. They have {@link areFieldPropsEqual | equivalent FieldProps}.
 * 3. They have the same exact set of allowed types. The allowed types must be (respectively) reference equal.
 *
 * For example, comparing an ImplicitFieldSchema that is a {@link TreeNodeSchema} to an ImplicitFieldSchema that is a {@link FieldSchema}
 * will return true if they are the same kind, the FieldSchema has exactly one allowed type (the TreeNodeSchema), and they have equivalent FieldProps.
 */
export function areImplicitFieldSchemaEqual(a, b) {
    return areFieldSchemaEqual(normalizeFieldSchema(a), normalizeFieldSchema(b));
}
/**
 * Returns true if the given {@link FieldSchema} are equivalent, otherwise false.
 * @remarks Two FieldSchema are considered equivalent if all of the following are true:
 * 1. They have the same {@link FieldKind | kinds}.
 * 2. They have {@link areFieldPropsEqual | equivalent FieldProps}.
 * 3. They have the same exact set of allowed types. The allowed types must be reference equal.
 */
export function areFieldSchemaEqual(a, b) {
    if (a === b) {
        return true;
    }
    if (a.kind !== b.kind) {
        return false;
    }
    if (!areFieldPropsEqual(a.props, b.props)) {
        return false;
    }
    return compareSets({ a: a.allowedTypeSet, b: b.allowedTypeSet });
}
/**
 * Returns true if the given {@link FieldProps} are equivalent, otherwise false.
 * @remarks FieldProps are considered equivalent if their keys and default providers are reference equal, and their metadata are {@link areMetadataEqual | equivalent}.
 */
function areFieldPropsEqual(a, b) {
    if (a === b) {
        return true;
    }
    if (a?.key !== b?.key || a?.defaultProvider !== b?.defaultProvider) {
        return false;
    }
    if (!areMetadataEqual(a?.metadata, b?.metadata)) {
        return false;
    }
    return true;
}
/**
 * Returns true if the given {@link FieldSchemaMetadata} are equivalent, otherwise false.
 * @remarks FieldSchemaMetadata are considered equivalent if their custom data and descriptions are (respectively) reference equal.
 */
function areMetadataEqual(a, b) {
    if (a === b) {
        return true;
    }
    return (Object.is(a?.custom, b?.custom) &&
        a?.description === b?.description &&
        arePersistedMetadataEqual(a?.persistedMetadata, b?.persistedMetadata));
}
/**
 * Returns true if the given persisted metadata fields are equivalent, otherwise false.
 * @remarks
 * Currently only handles shallow equality in the case where the keys are in the same order. This is acceptable for current use cases.
 */
function arePersistedMetadataEqual(a, b) {
    if (Object.is(a, b)) {
        return true;
    }
    if (a === undefined || b === undefined) {
        return false;
    }
    // Note that the key order matters. If `a` and `b` have the same content but the keys are in a different order,
    // this method will return false.
    const aStringified = JSON.stringify(a);
    const bStringified = JSON.stringify(b);
    return aStringified === bStringified;
}
//# sourceMappingURL=fieldSchema.js.map