/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert, Lazy } from "@fluidframework/core-utils/internal";
import { UsageError } from "@fluidframework/telemetry-utils/internal";
import { MapNodeStoredSchema } from "../../../core/index.js";
import { isTreeValue, } from "../../../feature-libraries/index.js";
import { brand, count, isReadonlyArray, } from "../../../util/index.js";
import { CompatibilityLevel, getKernel, NodeKind, 
// eslint-disable-next-line import-x/no-deprecated
typeNameSymbol, typeSchemaSymbol, getInnerNode, normalizeAllowedTypes, TreeNodeValid, privateDataSymbol, createTreeNodeSchemaPrivateData, AnnotatedAllowedTypesInternal, } from "../../core/index.js";
import { getTreeNodeSchemaInitializedData } from "../../createContext.js";
import { createFieldSchema, FieldKind } from "../../fieldSchema.js";
import { tryGetTreeNodeForField } from "../../getTreeNodeForField.js";
import { prepareForInsertion } from "../../prepareForInsertion.js";
import { unhydratedFlexTreeFromInsertable, } from "../../unhydratedFlexTreeFromInsertable.js";
import { recordLikeDataToFlexContent } from "../common.js";
// TreeMapNode is invariant over schema type, so for this handler to work with all schema, the only possible type for the schema is `any`.
// This is not ideal, but no alternatives are possible.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const handler = {
    getPrototypeOf: () => {
        return Map.prototype;
    },
};
class CustomMapNodeBase extends TreeNodeValid {
    constructor(input) {
        super(input ?? []);
    }
    [Symbol.iterator]() {
        return this.entries();
    }
    get innerNode() {
        return getInnerNode(this);
    }
    editor(key) {
        const field = this.innerNode.getBoxed(brand(key));
        return field.editor;
    }
    delete(key) {
        const field = this.innerNode.getBoxed(brand(key));
        this.editor(key).set(undefined, field.length === 0);
    }
    *entries() {
        const node = this.innerNode;
        for (const key of node.keys()) {
            yield [
                key,
                tryGetTreeNodeForField(node.getBoxed(key)),
            ];
        }
    }
    get(key) {
        const node = this.innerNode;
        const field = node.getBoxed(brand(key));
        return tryGetTreeNodeForField(field);
    }
    has(key) {
        return this.innerNode.tryGetField(brand(key)) !== undefined;
    }
    keys() {
        const node = this.innerNode;
        return node.keys();
    }
    set(key, value) {
        const kernel = getKernel(this);
        const node = this.innerNode;
        const innerSchema = this.innerNode.context.schema.nodeSchema.get(brand(kernel.schema.identifier));
        assert(innerSchema instanceof MapNodeStoredSchema, 0xc17 /* Expected MapNodeStoredSchema */);
        const mapTree = prepareForInsertion(value, createFieldSchema(FieldKind.Optional, kernel.schema.info), node.context, innerSchema.mapFields);
        const field = node.getBoxed(brand(key));
        this.editor(key).set(mapTree, field.length === 0);
        return this;
    }
    get size() {
        return count(this.innerNode.keys());
    }
    *values() {
        for (const [, value] of this.entries()) {
            yield value;
        }
    }
    forEach(callbackFn, thisArg) {
        for (const field of getInnerNode(this)) {
            const node = tryGetTreeNodeForField(field);
            callbackFn.call(thisArg, node, field.key, this);
        }
    }
}
CustomMapNodeBase.kind = NodeKind.Map;
/**
 * Define a {@link TreeNodeSchema} for a {@link (TreeArrayNode:interface)}.
 *
 * @param base - base schema type to extend.
 * @param useMapPrototype - should this type emulate a ES6 Map object (by faking its prototype with a proxy).
 * @param persistedMetadata - Optional persisted metadata for the object node schema.
 */
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export function mapSchema(identifier, info, implicitlyConstructable, useMapPrototype, nodeOptions = {}) {
    var _a;
    const normalizedTypes = normalizeAllowedTypes(info);
    const lazyAllowedTypesIdentifiers = new Lazy(() => new Set(normalizedTypes.evaluate().map((type) => type.identifier)));
    const lazySimpleAllowedTypes = new Lazy(() => {
        return AnnotatedAllowedTypesInternal.evaluateSimpleAllowedTypes(normalizedTypes);
    });
    let privateData;
    const persistedMetadata = nodeOptions.persistedMetadata;
    class Schema extends CustomMapNodeBase {
        constructor() {
            super(...arguments);
            this[_a] = "TreeMapNodeSchema";
        }
        static prepareInstance(instance, flexNode) {
            if (useMapPrototype) {
                return new Proxy(instance, handler);
            }
            return instance;
        }
        static buildRawNode(instance, input) {
            return unhydratedFlexTreeFromInsertable(input, this);
        }
        static get allowedTypesIdentifiers() {
            return lazyAllowedTypesIdentifiers.value;
        }
        static get simpleAllowedTypes() {
            return lazySimpleAllowedTypes.value;
        }
        static oneTimeSetup() {
            const schema = this;
            return getTreeNodeSchemaInitializedData(this, {
                shallowCompatibilityTest,
                toFlexContent: (data) => mapToFlexContent(data, schema),
            });
        }
        static get childTypes() {
            return normalizedTypes.evaluateSet();
        }
        // eslint-disable-next-line import-x/no-deprecated
        get [(_a = Symbol.toStringTag, typeNameSymbol)]() {
            return identifier;
        }
        get [typeSchemaSymbol]() {
            return Schema.constructorCached?.constructor;
        }
        static get [privateDataSymbol]() {
            return (privateData ??= createTreeNodeSchemaPrivateData(this, [normalizedTypes]));
        }
    }
    Schema.constructorCached = undefined;
    Schema.identifier = identifier;
    Schema.info = info;
    Schema.implicitlyConstructable = implicitlyConstructable;
    Schema.metadata = nodeOptions.metadata ?? {};
    Schema.persistedMetadata = persistedMetadata;
    const schemaErased = Schema;
    return schemaErased;
}
/**
 * {@link TreeNodeSchemaInitializedData.shallowCompatibilityTest} for Map nodes.
 */
function shallowCompatibilityTest(data) {
    if (isTreeValue(data)) {
        return CompatibilityLevel.None;
    }
    if (isReadonlyArray(data)) {
        // Arrays are iterable, so type checking does allow constructing a MapNode from an array if the array's type is key values pairs for the map.
        return CompatibilityLevel.Low;
    }
    if (Symbol.iterator in data) {
        return CompatibilityLevel.Normal;
    }
    // When not unioned with an ObjectNode, allow objects to be used to create maps.
    return CompatibilityLevel.Low;
}
/**
 * {@link TreeNodeSchemaInitializedData.toFlexContent} for Map nodes.
 *
 * Transforms data under a Map schema.
 * @param data - The tree data to be transformed. Must be an iterable or Record like object.
 * @param schema - The schema to comply with.
 */
function mapToFlexContent(data, schema) {
    if (!(typeof data === "object" && data !== null)) {
        throw new UsageError(`Input data is incompatible with Map schema: ${data}`);
    }
    const fieldsIterator = (Symbol.iterator in data
        ? // Support iterables of key value pairs (including Map objects)
            data
        : // Support record objects for JSON style Map data
            Object.entries(data));
    return recordLikeDataToFlexContent(fieldsIterator, schema);
}
//# sourceMappingURL=mapNode.js.map