/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils/internal";
import { FlexMapNodeSchema, isFlexTreeNode, } from "../feature-libraries/index.js";
import { getProxyForField, markContentType, prepareContentForInsert, } from "./proxies.js";
import { getFlexNode, setFlexNode } from "./proxyBinding.js";
import { getSimpleNodeSchema } from "./schemaCaching.js";
import { cursorFromNodeData } from "./toMapTree.js";
import { getFlexSchema } from "./toFlexSchema.js";
import { RawTreeNode, nodeContent, rawError } from "./rawNode.js";
// #region Create dispatch map for maps
export const mapStaticDispatchMap = {
    [Symbol.iterator]: {
        value() {
            return this.entries();
        },
    },
    delete: {
        value(key) {
            const node = getFlexNode(this);
            node.delete(key);
        },
    },
    entries: {
        *value() {
            const node = getFlexNode(this);
            for (const key of node.keys()) {
                yield [key, getProxyForField(node.getBoxed(key))];
            }
        },
    },
    get: {
        value(key) {
            const node = getFlexNode(this);
            const field = node.getBoxed(key);
            return getProxyForField(field);
        },
    },
    has: {
        value(key) {
            const node = getFlexNode(this);
            return node.has(key);
        },
    },
    keys: {
        value() {
            const node = getFlexNode(this);
            return node.keys();
        },
    },
    set: {
        value(key, value) {
            const node = getFlexNode(this);
            const content = prepareContentForInsert(value, node.context.forest);
            const classSchema = getSimpleNodeSchema(node.schema);
            const cursor = cursorFromNodeData(content, classSchema.info);
            node.set(key, cursor);
            return this;
        },
    },
    size: {
        get() {
            return getFlexNode(this).size;
        },
    },
    values: {
        *value() {
            for (const [, value] of this.entries()) {
                yield value;
            }
        },
    },
    forEach: {
        value(callbackFn, thisArg) {
            if (thisArg === undefined) {
                // We can't pass `callbackFn` to `FlexTreeMapNode` directly, or else the third argument ("map") will be a flex node instead of the proxy.
                getFlexNode(this).forEach((v, k, _) => callbackFn(v, k, this), thisArg);
            }
            else {
                const boundCallbackFn = callbackFn.bind(thisArg);
                getFlexNode(this).forEach((v, k, _) => boundCallbackFn(v, k, this), thisArg);
            }
        },
    },
    // TODO: add `clear` once we have established merge semantics for it.
};
const mapPrototype = Object.create(Object.prototype, mapStaticDispatchMap);
// #endregion
/**
 * @param allowAdditionalProperties - If true, setting of unexpected properties will be forwarded to the target object.
 * Otherwise setting of unexpected properties will error.
 * @param customTargetObject - Target object of the proxy.
 * If not provided `new Map()` is used for the target and a separate object created to dispatch map methods.
 * If provided, the customTargetObject will be used as both the dispatch object and the proxy target, and therefor must provide the map functionality from {@link mapPrototype}.
 */
export function createMapProxy(allowAdditionalProperties, customTargetObject) {
    // Create a 'dispatch' object that this Proxy forwards to instead of the proxy target.
    const dispatch = customTargetObject ??
        Object.create(mapPrototype, {
        // Empty - JavaScript Maps do not expose any "own" properties.
        });
    const targetObject = customTargetObject ?? new Map();
    // TODO: Although the target is an object literal, it's still worthwhile to try experimenting with
    // a dispatch object to see if it improves performance.
    const proxy = new Proxy(targetObject, {
        get: (target, key, receiver) => {
            // Pass the proxy as the receiver here, so that any methods on the prototype receive `proxy` as `this`.
            return Reflect.get(dispatch, key, proxy);
        },
        getOwnPropertyDescriptor: (target, key) => {
            return Reflect.getOwnPropertyDescriptor(dispatch, key);
        },
        has: (target, key) => {
            return Reflect.has(dispatch, key);
        },
        set: (target, key, newValue) => {
            return allowAdditionalProperties ? Reflect.set(dispatch, key, newValue) : false;
        },
        ownKeys: (target) => {
            // All of Map's properties are inherited via its prototype, so there is nothing to return here,
            return [];
        },
    });
    return proxy;
}
/**
 * Define a {@link TreeNodeSchema} for a {@link (TreeArrayNode:interface)}.
 *
 * @param name - Unique identifier for this schema including the factory's scope.
 */
export function mapSchema(base, customizable) {
    class schema extends base {
        constructor(input) {
            super(input);
            const proxyTarget = customizable ? this : undefined;
            const flexSchema = getFlexSchema(this.constructor);
            assert(flexSchema instanceof FlexMapNodeSchema, 0x917 /* invalid flex schema */);
            const flexNode = isFlexTreeNode(input)
                ? input
                : new RawMapNode(flexSchema, copyContent(flexSchema.name, input));
            const proxy = createMapProxy(customizable, proxyTarget);
            setFlexNode(proxy, flexNode);
            return proxy;
        }
    }
    // Setup map functionality
    Object.defineProperties(schema.prototype, mapStaticDispatchMap);
    return schema;
}
/**
 * The implementation of a map node created by {@link createRawNode}.
 */
export class RawMapNode extends RawTreeNode {
    get size() {
        return this[nodeContent].size;
    }
    has(key) {
        return this[nodeContent].has(key);
    }
    get(key) {
        return this[nodeContent].get(key);
    }
    keys() {
        return this[nodeContent].keys();
    }
    values() {
        throw rawError("Iterating map values");
    }
    entries() {
        throw rawError("Iterating map entries");
    }
    forEach(callbackFn, thisArg) {
        throw rawError("Iterating maps with forEach");
    }
    set(key, value) {
        throw rawError("Setting a map entry");
    }
    delete(key) {
        throw rawError("Deleting a map entry");
    }
    get asObject() {
        throw rawError("Converting a map to an object");
    }
    [Symbol.iterator]() {
        return this.entries();
    }
    boxedIterator() {
        throw rawError("Boxed iteration");
    }
}
function copyContent(typeName, content) {
    const copy = new Map(content);
    markContentType(typeName, copy);
    return copy;
}
//# sourceMappingURL=mapNode.js.map