import React, { useMemo } from 'react';
import { makeStyles, Typography } from '@material-ui/core';
import { Form, FormButtons, SubmitButton } from '../utilities/form';
import { getPrimaryKeyValues } from '../utilities/maintenanceEngine/CrudBrowserUtilities';
import { useCrudActions } from '../hooks/crudActions';
import { CardinalityTypeEnums } from '../enums/unitySystemEnums';
import PropTypes from 'prop-types';
const useStyles = makeStyles((theme) => ({
    root: {
        marginTop: theme.spacing(-2)
    },
    body: {
        marginTop: theme.spacing(2)
    },
    actions: {
        marginTop: theme.spacing(2),
        marginBottom: theme.spacing(2),
        display: 'flex',
        flexDirection: 'row'
    },
    title: {
        flexGrow: 1
    },
    divider: {
        marginTop: theme.spacing(2)
    },
    subject: {
        marginLeft: theme.spacing(1),
        display: 'flex',
        flexDirection: 'row',
        flexGrow: 1
    },
    switchRoot: {
        marginLeft: theme.spacing(1)
    },
    input: {
        height: 34,
        padding: 0
    },
    formTextInput: {
        fontSize: 13
    },
    labelRoot: {
        fontSize: 13
    }
}));
export const ActionForm = (props) => {
    const { entityAttributes, foreignKeyData, onCreate, closeSideSheet, onUpdate, crudTableEditionData, crudTableFormData, udpFieldInfos } = props;
    const classes = useStyles();
    const { renderInputByFieldType } = useCrudActions();
    const primaryKeyValues = useMemo(() => getPrimaryKeyValues(entityAttributes, crudTableEditionData), [entityAttributes, crudTableEditionData]);
    // we'll need this to determine which property names are used as keys for many-to-many
    const manyToManyPropertyList = useMemo(() => {
        if (!(entityAttributes === null || entityAttributes === void 0 ? void 0 : entityAttributes.length))
            return [];
        const mtmPropertyList = new Set();
        entityAttributes.forEach((attr) => {
            var _a;
            if ((_a = attr === null || attr === void 0 ? void 0 : attr.extendedProperties) === null || _a === void 0 ? void 0 : _a.childEntity) {
                Object.keys(attr.extendedProperties.childEntityAssoc || {}).length &&
                    attr.extendedProperties.childEntityAssoc.Cardinality ===
                        CardinalityTypeEnums.Many_To_Many &&
                    attr.extendedProperties.childEntityAssoc.Keys.forEach((value, i) => {
                        const name = value.split(',')[0];
                        if (name) {
                            // check name string: if 1 word, lowercase. if 2 words, lower first char
                            mtmPropertyList.add(name.toLowerCase());
                        }
                    });
            }
        });
        return mtmPropertyList;
    }, [entityAttributes]);
    const handleSubmit = async (values) => {
        let newTableData = Object.assign(Object.assign({}, crudTableFormData), values);
        // remove identifiers from object
        entityAttributes
            .filter((ea) => {
            var _a;
            return (_a = ea === null || ea === void 0 ? void 0 : ea.extendedProperties) === null || _a === void 0 ? void 0 : _a.identifier;
        })
            .forEach((ea) => {
            delete newTableData[ea.name];
        });
        // transform values by fkData before creating/updating
        foreignKeyData.forEach((fkd) => {
            Object.keys(newTableData).forEach((key) => {
                var _a;
                if (key === fkd.fieldName) {
                    newTableData[key] = (_a = fkd.data.find((d) => d.id === newTableData[key].id)) === null || _a === void 0 ? void 0 : _a.id;
                }
            });
        });
        const isNewRow = !crudTableEditionData;
        if (isNewRow) {
            onCreate && (await onCreate(newTableData));
        }
        else {
            onUpdate && (await onUpdate(newTableData, primaryKeyValues));
        }
        closeSideSheet && closeSideSheet();
    };
    const isNewEntry = useMemo(() => !crudTableEditionData, [crudTableEditionData]);
    return (React.createElement(Form, { onSubmit: handleSubmit }, React.createElement("div", null, entityAttributes === null || entityAttributes === void 0 ? void 0 : entityAttributes.map((schemaAttribute, index) => {
        var _a;
        const fieldInfo = udpFieldInfos === null || udpFieldInfos === void 0 ? void 0 : udpFieldInfos.find((fi) => {
            var _a;
            return (fi === null || fi === void 0 ? void 0 : fi.name.toLowerCase()) === ((_a = schemaAttribute === null || schemaAttribute === void 0 ? void 0 : schemaAttribute.name) === null || _a === void 0 ? void 0 : _a.toLowerCase());
        });
        // If the field is an identity and is Updating form, we will make the field readOnly
        if ((fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.isPrimaryKey) && !isNewEntry) {
            schemaAttribute.disabled = true;
        }
        if ((fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.isPrimaryKey) && isNewEntry && !(fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.isIdentity)) {
            schemaAttribute.disabled = false;
        }
        return (!((_a = schemaAttribute === null || schemaAttribute === void 0 ? void 0 : schemaAttribute.extendedProperties) === null || _a === void 0 ? void 0 : _a.identifier) && (React.createElement(React.Fragment, { key: `${schemaAttribute.name}-${index}` }, React.createElement(Typography, { variant: "subtitle2", style: { marginTop: 8 } }, schemaAttribute.friendlyName), renderInputByFieldType(schemaAttribute, index, entityAttributes, fieldInfo, foreignKeyData, null, crudTableFormData, classes, false, null, manyToManyPropertyList))));
    })), React.createElement(FormButtons, null, React.createElement(SubmitButton, { variant: "contained", color: "secondary", disablePristine: false, disabled: false, style: { marginTop: 15 } }, "Sav"))));
};
ActionForm.propTypes = {
    /**
     * Entity attributes for selected entity within catalog
     */
    entityAttributes: PropTypes.array,
    /**
     * Foreign key data for selected entity within catalog
     */
    foreignKeyData: PropTypes.array,
    /**
     * Entity data
     */
    crudTableEditionData: PropTypes.array,
    /**
     * onClick event for closing sidesheet
     */
    closeSideSheet: PropTypes.func,
    /**
     * onClick event for creating
     */
    onCreate: PropTypes.func,
    /**
     * onClick event for updating
     */
    onUpdate: PropTypes.func
};
//# sourceMappingURL=ActionForm.js.map