import React, { useContext } from "react";
import { isObjectType } from "../schema";
import { CollapsibleItemTemplate } from "./array-field-collapsible-item";
import { SimpleItemTemplate } from "./array-field-simple-item";
import { ArrayFieldContext } from "./array-context";
export const ArrayFieldItemTemplate = (props) => {
    const arrayContext = useContext(ArrayFieldContext);
    const schema = arrayContext === null || arrayContext === void 0 ? void 0 : arrayContext.arraySchema;
    const formData = arrayContext === null || arrayContext === void 0 ? void 0 : arrayContext.formData;
    const formContext = props.registry.formContext;
    const allowItemReorder = canItemReorder(props, schema);
    const allowItemRemoval = canRemoveItems(schema);
    if (schema && isObjectType(schema.items)) {
        const itemData = Array.isArray(formData)
            ? formData[props.index]
            : undefined;
        return React.createElement(CollapsibleItemTemplate, {
            key: props.itemKey,
            buttonsProps: props.buttonsProps,
            index: props.index,
            data: itemData,
            schema: schema,
            formSchema: formContext === null || formContext === void 0 ? void 0 : formContext.schema,
            allowItemRemoval: allowItemRemoval,
            allowItemReorder: allowItemReorder,
        }, props.children);
    }
    return React.createElement(SimpleItemTemplate, {
        key: props.itemKey,
        buttonsProps: props.buttonsProps,
        index: props.index,
        allowItemRemoval: allowItemRemoval,
        allowItemReorder: allowItemReorder,
    }, props.children);
};
function canRemoveItems(schema) {
    const limeOptions = (schema === null || schema === void 0 ? void 0 : schema.lime) || {};
    return limeOptions.allowItemRemoval !== false;
}
function canItemReorder(props, schema) {
    const limeOptions = (schema === null || schema === void 0 ? void 0 : schema.lime) || {};
    if (limeOptions.allowItemReorder === false) {
        return false;
    }
    const { buttonsProps } = props;
    return Boolean((buttonsProps === null || buttonsProps === void 0 ? void 0 : buttonsProps.hasMoveDown) || (buttonsProps === null || buttonsProps === void 0 ? void 0 : buttonsProps.hasMoveUp));
}
