import { createTrait } from '@meta-ui/core';
import { Type } from '@sinclair/typebox';
const HasInitializedMap = new Map();
const ArrayStateTrait = ({ key, initialValue, componentId, mergeState, subscribeMethods, services, }) => {
    const hashId = `#${componentId}@${key}`;
    const hasInitialized = HasInitializedMap.get(hashId);
    if (!hasInitialized) {
        mergeState({ [key]: initialValue });
        const methods = {
            setArray({ key, value }) {
                mergeState({ [key]: value });
            },
            deleteItemByIndex({ key, index }) {
                const _arr = [...services.stateManager.store[componentId][key]];
                _arr.splice(index, 1);
                mergeState({ [key]: _arr });
            },
            deleteItemById({ key, itemIdKey, itemId, }) {
                const _arr = [...services.stateManager.store[componentId][key]].filter(item => {
                    return item[itemIdKey] !== itemId;
                });
                mergeState({ [key]: _arr });
            },
        };
        subscribeMethods(methods);
        HasInitializedMap.set(hashId, true);
    }
    return {
        props: null,
    };
};
const PropsSchema = Type.Object({
    key: Type.String(),
    initialValue: Type.Array(Type.Any()),
});
export default Object.assign(Object.assign({}, createTrait({
    version: 'core/v1',
    metadata: {
        name: 'arrayState',
        description: 'add array state to component',
    },
    spec: {
        properties: PropsSchema,
        state: Type.Any(),
        methods: [
            {
                name: 'setArray',
                parameters: Type.Object({
                    key: Type.String(),
                    value: Type.Array(Type.Any()),
                }),
            },
            {
                name: 'deleteItemByIndex',
                parameters: Type.Object({
                    key: Type.String(),
                    index: Type.Integer(),
                }),
            },
            {
                name: 'deleteItemById',
                parameters: Type.Object({
                    key: Type.String(),
                    itemIdKey: Type.String(),
                    itemId: Type.String(),
                }),
            },
            {
                name: 'reset',
            },
        ],
    },
})), { impl: ArrayStateTrait });
//# sourceMappingURL=arrayState.js.map