import { Form } from "../../../../utilities/form/Form.mjs";
import { FormSpy } from "../../../../utilities/form/FormSpy.mjs";
import { ConfigService } from "../../../../configService/index.mjs";
import { CardinalityTypeEnums, TransactionUiActionTypeEnums } from "../../../../enums/unitySystemEnums.mjs";
import { useHandleAxiosSnackbar } from "../../../../utilities/apiHelpers.mjs";
import { apiMutate, useAxiosMutate } from "../../../../utilities/useAxiosMutate.mjs";
import { getSanitizedName } from "../../../../utilities/entities/entityUtilities.mjs";
import { AmbientCard } from "../../../../UI/surfaces/cards/AmbientCard/AmbientCard.mjs";
import EditTransactionDetailsFormFields from "./DynamicTransactionDomainFormFields.mjs";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { LinearProgress } from "@material-ui/core";
import { useTranslation } from "react-i18next";
//#region src/udp/pages/UdpTransactionsPage/components/DynamicTransactionDomainForm.jsx
const DynamicTransactionDomainForm = (props) => {
	const { transaction, formRef, domainName, transactionTypeId, transactionUiActionType, setHasUnsavedChanges, onSubmitSuccess, refetchTransaction, catalogObject } = props;
	const [entityAttributes, setEntityAttributes] = useState(null);
	const fullyQualifiedName = transaction?.entityBusinessKey?.split("|")[0];
	const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
	const { t } = useTranslation();
	const [{ data: udpObjectInfo }, fetchUdpObjectInfo] = useAxiosMutate(ConfigService.productV1ApiUrl, `UdpObjectInfo/search`, {
		method: "post",
		data: {
			eagerLoad: true,
			pageNumber: 1,
			pageSize: 50,
			filterElements: [{
				searchField: "sanitizedName",
				searchOperator: "=",
				searchValue: fullyQualifiedName ? getSanitizedName(fullyQualifiedName) : domainName
			}]
		}
	});
	const updateFieldInfo = (tableEntries, catalogObjectFieldInfo, fkFieldInfo, fkDomainName) => {
		let updatedFields = {
			type: "array",
			options: tableEntries,
			domainName: fkDomainName
		};
		const updatedFieldInfo = {
			...fkFieldInfo,
			...updatedFields
		};
		const index = catalogObjectFieldInfo.findIndex((f) => f.name.toLowerCase() === fkFieldInfo.name.toLowerCase());
		if (index != -1) catalogObjectFieldInfo[index] = updatedFieldInfo;
	};
	const mergeCatalogObjectInfoFieldInfo = useCallback((entityCatalogObjectInfo, filteredEntityFieldInfo) => {
		return entityCatalogObjectInfo.map((entityCatalogObject) => {
			let matchingEntityFieldInfo = filteredEntityFieldInfo.find((fieldInfo) => {
				let formattedFieldName = fieldInfo.name.slice(0, 1).toLowerCase() + fieldInfo.name.slice(1);
				if (fieldInfo.name == "ID") formattedFieldName = formattedFieldName.toLowerCase();
				return formattedFieldName == entityCatalogObject.name;
			});
			if (matchingEntityFieldInfo) {
				let additional_fields = {
					hidden: matchingEntityFieldInfo.properties.maintainenceConfig.hidden,
					associationLabel: matchingEntityFieldInfo.properties.maintainenceConfig.associationLabel,
					isPrimaryKey: matchingEntityFieldInfo.isPrimaryKey
				};
				return {
					...entityCatalogObject,
					...additional_fields
				};
			} else return entityCatalogObject;
		});
	}, []);
	const filterOutManyToManyRelationships = (CatalogObjectInfo) => {
		return CatalogObjectInfo.filter((catalogObject_0) => {
			const cardinality = catalogObject_0.extendedProperties?.childEntityAssoc?.Cardinality;
			if (cardinality != void 0) return cardinality != CardinalityTypeEnums.Many_To_Many && cardinality != CardinalityTypeEnums.One_To_One && catalogObject_0.name.toLowerCase() != "businessobjectkey";
			else return catalogObject_0.name.toLowerCase() != "businessobjectkey";
		});
	};
	const updateFkFields = useCallback(async (entityCatalogObjectInfo_1, catalogObjectInfo) => {
		const childEntityAssociation = catalogObjectInfo.extendedProperties.childEntityAssoc;
		if (childEntityAssociation.Cardinality != void 0) {
			const foreignKeyAssociationFields = childEntityAssociation.Keys[0].split(",");
			let fieldsInAssociationToIgnore = [
				"id",
				"businessobjectkey",
				"entitybusinesskey"
			];
			return Promise.all(foreignKeyAssociationFields.map(async (fkFieldName) => {
				if (fkFieldName.toLowerCase() != "id" && !fieldsInAssociationToIgnore.includes(fkFieldName.toLowerCase())) {
					let fkFieldInfo_0 = entityCatalogObjectInfo_1.find((field) => field.name.toLowerCase() == fkFieldName.toLowerCase());
					const fkDomainName_0 = getSanitizedName(childEntityAssociation.TargetType);
					try {
						const getTableEntriesResp = await apiMutate(ConfigService.productV1ApiUrl, `${fkDomainName_0}`, { method: "get" });
						if (getTableEntriesResp.data.length > 0 && fkFieldInfo_0) updateFieldInfo(getTableEntriesResp.data, entityCatalogObjectInfo_1, fkFieldInfo_0, fkDomainName_0);
					} catch (error) {
						handleErrorSnackbar(new Error(t(`Error finiding field information! Please try again.`)));
					}
				}
			}));
		}
	}, [handleErrorSnackbar, t]);
	const filterAdjustEntityAttributes = useCallback(async (catalogObjectInfo_0) => {
		let entityCatalogObjectInfo_2 = catalogObjectInfo_0;
		entityCatalogObjectInfo_2 = filterOutManyToManyRelationships(entityCatalogObjectInfo_2);
		let filteredEntityFieldInfo_0 = (await fetchUdpObjectInfo()).data.pageList[0].objectFieldInfo.filter((fieldInfo_0) => fieldInfo_0.properties.isDefaultVisible);
		await Promise.all(entityCatalogObjectInfo_2.map((catalogObjectInfo_1) => {
			return updateFkFields(entityCatalogObjectInfo_2, catalogObjectInfo_1);
		}));
		entityCatalogObjectInfo_2 = entityCatalogObjectInfo_2.filter((catalogObject_1) => !catalogObject_1.extendedProperties.childEntity);
		return mergeCatalogObjectInfoFieldInfo(entityCatalogObjectInfo_2, filteredEntityFieldInfo_0);
	}, [
		fetchUdpObjectInfo,
		mergeCatalogObjectInfoFieldInfo,
		updateFkFields
	]);
	useEffect(() => {
		if (catalogObject) filterAdjustEntityAttributes(catalogObject.properties).then((filteredResp) => {
			setEntityAttributes(filteredResp);
		});
	}, [filterAdjustEntityAttributes, catalogObject]);
	const executeSaveChanges = useCallback(async (data) => apiMutate(ConfigService.productV1ApiUrl, `udpTransaction/${transaction?.transactionId}/saveChanges`, { method: "put" }, data), [transaction?.transactionId]);
	const executeCreateTransactionAndDomain = useCallback(async (data_0) => apiMutate(ConfigService.productV1ApiUrl, `udpTransaction/transactionType/${transactionTypeId}/create`, { method: "post" }, data_0), [transactionTypeId]);
	const onSubmit = useCallback(async (values) => {
		try {
			const request = { data: values };
			let response = null;
			let successMessageAction = "";
			let errorMessageAction = "";
			if (transactionUiActionType == TransactionUiActionTypeEnums.Render_Transaction_Details_Page) {
				response = await executeSaveChanges({ data: values });
				successMessageAction = "saved";
				errorMessageAction = "saving";
			} else if (transactionUiActionType == TransactionUiActionTypeEnums.Render_Create_Transaction_Page) {
				response = await executeCreateTransactionAndDomain(request);
				successMessageAction = "created";
				errorMessageAction = "creating";
			}
			const { status, data: data_1 } = response || {};
			const apiResult = data_1?.actionApiResult;
			if (status === 200) {
				if (!apiResult || apiResult.success) {
					handleSuccessSnackbar(t(`Transaction has been ${successMessageAction} successfully`));
					onSubmitSuccess?.(response);
				} else if (apiResult?.errorMessage) handleErrorSnackbar(new Error(apiResult.errorMessage));
			} else {
				const defaultError = t(`Error ${errorMessageAction} Transaction. Please try again later.`);
				handleErrorSnackbar(new Error(defaultError));
			}
		} catch (error_0) {
			handleErrorSnackbar(error_0);
		} finally {
			if (setHasUnsavedChanges) {
				formRef.current?.form?.restart(values);
				setHasUnsavedChanges(false);
			}
			if (refetchTransaction) refetchTransaction();
		}
	}, [
		executeSaveChanges,
		executeCreateTransactionAndDomain,
		handleSuccessSnackbar,
		handleErrorSnackbar,
		t,
		transactionUiActionType,
		setHasUnsavedChanges,
		formRef,
		onSubmitSuccess,
		refetchTransaction
	]);
	const fieldAttributes = useMemo(() => {
		if (!entityAttributes) return [];
		return entityAttributes;
	}, [entityAttributes]);
	return fieldAttributes.length == 0 ? /* @__PURE__ */ React.createElement(LinearProgress, null) : /* @__PURE__ */ React.createElement(AmbientCard, { fullWidth: true }, /* @__PURE__ */ React.createElement(Form, {
		onSubmit,
		ref: formRef
	}, /* @__PURE__ */ React.createElement(FormSpy, { subscription: { dirty: true } }, ({ dirty }) => {
		if (setHasUnsavedChanges) setHasUnsavedChanges(dirty);
	}), /* @__PURE__ */ React.createElement(EditTransactionDetailsFormFields, {
		transaction,
		fieldAttributes,
		transactionTypeId
	})));
};
//#endregion
export { DynamicTransactionDomainForm as default };

//# sourceMappingURL=DynamicTransactionDomainForm.mjs.map