import { Field } from "../utilities/form/Field.mjs";
import { ConfigService } from "../configService/index.mjs";
import { apiMutate } from "../utilities/useAxiosMutate.mjs";
import { DateTimeField } from "../UI/inputs/datetimes/DateTimeField.mjs";
import { FluentTextFieldAutoComplete } from "../UI/inputs/textField/FluentTextFieldAutoComplete.mjs";
import { FluentToggle } from "../UI/inputs/toggle/FluentToggle.mjs";
import { PropertyTypeEnum } from "../enums/propertyTypeEnums.mjs";
import { InputFieldType } from "../enums/InputFieldTypeEnums.mjs";
import { toLowerFirstChar, toTitleCase } from "../utilities/input/StringUtilities.mjs";
import { FluentColorPicker } from "../UI/inputs/pickers/FluentColorPicker.mjs";
import { getSanitizedName } from "../utilities/entities/entityUtilities.mjs";
import React, { useCallback } from "react";
import { FormControlLabel, TextField } from "@material-ui/core";
//#region src/hooks/crudActions.jsx
function useCrudActions() {
	const renderInputByForeignKey = useCallback((foreignKeyData, setFkData, crudTableFormData, schemaAttribute, index, isNewEntry, entityData, label = "", manyToManyPropertyList = /* @__PURE__ */ new Set()) => {
		const foreignKeyAttributeName = toLowerFirstChar(schemaAttribute.name);
		if (!foreignKeyData) return;
		let attributeData = foreignKeyData.find((fkd) => fkd.fieldName === foreignKeyAttributeName)?.data;
		return (!schemaAttribute.extendedProperties.identifier || isNewEntry) && /* @__PURE__ */ React.createElement(Field, {
			component: FluentTextFieldAutoComplete,
			id: `${schemaAttribute.name}${index}`,
			initialValue: attributeData ? attributeData.find((d) => d.id === crudTableFormData[foreignKeyAttributeName]) : 0,
			label: toTitleCase(label),
			name: foreignKeyAttributeName,
			fullWidth: true,
			variant: "outlined",
			margin: "normal",
			options: attributeData || [],
			optionKey: "name",
			required: !schemaAttribute?.nullable,
			style: { marginTop: 8 },
			disabled: schemaAttribute?.disabled
		});
	}, []);
	return {
		renderInputByForeignKey,
		renderInputByFieldType: useCallback((schemaAttribute_0, index_0, attributes, fieldInfo, foreignKeyData_0, setFkData_0, crudTableFormData_0, classes, isNewEntry_0, entityData_0, manyToManyPropertyList_0) => {
			const NUMBER_TYPE = [
				PropertyTypeEnum.Int,
				PropertyTypeEnum.Long,
				PropertyTypeEnum.Double
			];
			if (schemaAttribute_0?.name === "clusterId") return;
			const ceAttributes = attributes.filter((ea) => ea.extendedProperties.childEntity);
			if (schemaAttribute_0.type === "bool" && crudTableFormData_0[toLowerFirstChar(schemaAttribute_0.name)] === "") crudTableFormData_0[toLowerFirstChar(schemaAttribute_0.name)] = false;
			const attribute = ceAttributes.find((ceAttr) => Object.keys(ceAttr?.extendedProperties?.childEntityAssoc || {}).length && ceAttr.extendedProperties.childEntityAssoc.Keys.find((a) => {
				const fieldId = a.split(",")[0];
				return (/^[A-Z]*$/.test(fieldId) ? fieldId.toLowerCase() : toLowerFirstChar(fieldId)) === toLowerFirstChar(schemaAttribute_0.name);
			}));
			if ((schemaAttribute_0?.isForeignKey || attribute) && !(!attribute?.extendedProperties?.childEntityAssoc?.IsJoiningObject && attribute?.extendedProperties?.childEntityAssoc?.Cardinality === 2) && attribute?.extendedProperties?.childEntityAssoc?.Cardinality !== 3) {
				const label_0 = fieldInfo?.properties?.displayName ? fieldInfo.properties.displayName : attribute?.reference ? getSanitizedName(attribute.reference) : "";
				console.log(label_0);
				return renderInputByForeignKey(foreignKeyData_0, setFkData_0, crudTableFormData_0, schemaAttribute_0, index_0, isNewEntry_0, entityData_0, label_0, manyToManyPropertyList_0);
			}
			const maintainenceConfig = fieldInfo?.properties?.maintainenceConfig;
			const displayLabel = toTitleCase(fieldInfo?.properties?.displayName || schemaAttribute_0.name);
			const defaultFieldType = schemaAttribute_0?.type;
			const disabled = schemaAttribute_0?.disabled || maintainenceConfig?.readOnly || schemaAttribute_0?.extendedProperties?.readOnly;
			let fieldIsNumberType = maintainenceConfig?.renderAs === InputFieldType.Number;
			const required = !schemaAttribute_0?.nullable || fieldInfo?.isPrimaryKey && !disabled || disabled;
			const DefaultTextField = /* @__PURE__ */ React.createElement(Field, {
				component: TextField,
				id: `${schemaAttribute_0.name}${index_0}`,
				name: toLowerFirstChar(schemaAttribute_0.name),
				label: displayLabel,
				initialValue: crudTableFormData_0[toLowerFirstChar(schemaAttribute_0.name)] !== null ? crudTableFormData_0[toLowerFirstChar(schemaAttribute_0.name)] : "",
				type: fieldIsNumberType && "number",
				fullWidth: true,
				variant: "outlined",
				size: "small",
				required,
				margin: "dense",
				InputProps: { classes: {
					root: classes?.input,
					input: classes?.formTextInput
				} },
				inputProps: { udprecordid: `udpRecord-crudActions-${schemaAttribute_0.name}${index_0}` },
				InputLabelProps: { classes: { root: classes?.labelRoot } },
				disabled
			});
			const DefaultFluentToggle = /* @__PURE__ */ React.createElement(FormControlLabel, {
				control: /* @__PURE__ */ React.createElement(Field, {
					component: FluentToggle,
					type: "checkbox",
					id: `${schemaAttribute_0.name}${index_0}`,
					disabled,
					classes: { root: classes?.switchRoot },
					name: toLowerFirstChar(schemaAttribute_0.name),
					color: "secondary",
					inputProps: { "aria-label": "Active condition" },
					initialValue: typeof crudTableFormData_0[toLowerFirstChar(schemaAttribute_0.name)] === "boolean" ? crudTableFormData_0[toLowerFirstChar(schemaAttribute_0.name)] : crudTableFormData_0[toLowerFirstChar(schemaAttribute_0.name)] === "true" ? true : false
				}),
				label: displayLabel,
				labelPlacement: "start",
				style: { marginLeft: 4 }
			});
			const DefaultFluentDatePicker = /* @__PURE__ */ React.createElement(Field, {
				disabled,
				component: DateTimeField,
				id: `${schemaAttribute_0.name}${index_0}`,
				name: toLowerFirstChar(schemaAttribute_0.name),
				label: displayLabel,
				initialValue: crudTableFormData_0[toLowerFirstChar(schemaAttribute_0.name)] ? new Date(crudTableFormData_0[toLowerFirstChar(schemaAttribute_0.name)]) : "",
				fullWidth: true,
				variant: "outlined",
				size: "small",
				required,
				style: { marginTop: 8 }
			});
			const DefaultFluentColorPicker = /* @__PURE__ */ React.createElement(FormControlLabel, {
				control: /* @__PURE__ */ React.createElement(Field, {
					component: FluentColorPicker,
					id: `${schemaAttribute_0.name}${index_0}`,
					name: toLowerFirstChar(schemaAttribute_0.name),
					initialValue: crudTableFormData_0[toLowerFirstChar(schemaAttribute_0.name)] || "",
					fullWidth: true,
					variant: "outlined",
					size: "small",
					required,
					margin: "dense",
					InputProps: { classes: {
						root: classes?.input,
						input: classes?.formTextInput
					} },
					InputLabelProps: { classes: { root: classes?.labelRoot } },
					disabled
				}),
				label: displayLabel,
				labelPlacement: "start",
				style: { marginLeft: 4 }
			});
			if (maintainenceConfig?.hiddenForm) return null;
			switch (maintainenceConfig?.renderAs) {
				case InputFieldType.Text:
				case InputFieldType.Number: return DefaultTextField;
				case InputFieldType.Toggle: return DefaultFluentToggle;
				case InputFieldType.DateTime: return DefaultFluentDatePicker;
				case InputFieldType.ColorPicker: return DefaultFluentColorPicker;
				case InputFieldType.Default:
				default:
					fieldIsNumberType = NUMBER_TYPE.includes(defaultFieldType);
					switch (defaultFieldType) {
						case PropertyTypeEnum.Int:
						case PropertyTypeEnum.Long:
						case PropertyTypeEnum.Double:
						case PropertyTypeEnum.String:
						case PropertyTypeEnum.String_Uuid: return DefaultTextField;
						case PropertyTypeEnum.Boolean: return DefaultFluentToggle;
						case PropertyTypeEnum.DateTime: return DefaultFluentDatePicker;
						default: return null;
					}
			}
		}, [renderInputByForeignKey]),
		getFKData: useCallback(async (fkMethods, setForeignKeyData, enqueueSnackbar, displayToasts) => {
			let fkData = [];
			let promises = [];
			let promiseDetails = [];
			fkMethods.forEach((method) => {
				if (method && method?.entity?.unityBaseGetAllMethod) {
					promiseDetails.push({
						url: ConfigService.integrationV1ApiUrl + `/apimethod/executeQueryWithParameters/${method?.entity?.unityBaseGetAllMethod?.apiMethodId}`,
						fieldName: method.fkName,
						name: method.entity.entityName
					});
					promises.push(apiMutate(ConfigService.integrationV1ApiUrl, `apimethod/executeQueryWithParameters/${method?.entity?.unityBaseGetAllMethod?.apiMethodId}`, { method: "post" }, { data: {} }));
				} else if (displayToasts) enqueueSnackbar(`${method.entity.entityName}'s Get-All method needs to be promoted`, {
					variant: "error",
					anchorOrigin: {
						vertical: "top",
						horizontal: "center"
					}
				});
				else console.warn(`${method.entity.entityName}'s Get-All method needs to be promoted`);
			});
			Promise.all(promises).then((resp) => {
				resp.forEach((response, index_1) => {
					if (response.status === 200) {
						if (response?.data) {
							let respData = [];
							response.data.forEach((d_0) => {
								respData.push({
									id: d_0.id,
									name: d_0.name ?? d_0.id
								});
							});
							const promiseDetail = promiseDetails.find((p) => p.url === response?.config?.url);
							fkData.push({
								fieldName: promiseDetail.fieldName,
								name: promiseDetail.fieldName,
								data: respData
							});
						}
					}
				});
				setForeignKeyData(fkData);
			});
		}, [])
	};
}
//#endregion
export { useCrudActions };

//# sourceMappingURL=crudActions.mjs.map