import { getSanitizedName } from "../../utilities/entities/entityUtilities.mjs";
import { usePromotedMethodEntity } from "../../hooks/usePromotedMethodEntity.mjs";
import { executeQueryAdHoc, executeQueryWithParameters } from "../utilities/methodUtils.mjs";
import { useCallback, useEffect, useState } from "react";
//#region src/udp/export/useUdpExport.js
const useUdpExport = (apiCatalogId, productId) => {
	const [entity, setEntity] = useState();
	const [searchObject, setSearchObject] = useState();
	const [fileFormat, setFileFormat] = useState(".XLSX");
	const [numRowsToExport, setNumRowsToExport] = useState(null);
	const [validSearch, setValidSearch] = useState(false);
	const [errorList, setErrorList] = useState([]);
	const [activeExportJob, setActiveExportJob] = useState();
	const [exportLoading, setExportLoading] = useState(false);
	const [fileResultData, setFileResultData] = useState();
	const { data: selectedEntity, loading: entityLoading } = usePromotedMethodEntity(entity, true, apiCatalogId, productId);
	const { data: udpJobEntity } = usePromotedMethodEntity("udpJob", true, apiCatalogId, productId);
	const refetchActiveJobData = useCallback(async () => {
		if (udpJobEntity?.unityBaseGetMethod?.apiMethodId) await executeQueryWithParameters({ data: { id: activeExportJob?.id } }, udpJobEntity?.unityBaseGetMethod?.apiMethodId).then((res) => {
			setActiveExportJob(res.data);
		}).catch((err) => {
			addErrorIfNotExists("jobstatus", "Error getting job status ", "error");
		});
	}, [activeExportJob?.id, udpJobEntity?.unityBaseGetMethod?.apiMethodId]);
	const refetchfileResultData = useCallback(async () => {
		if (udpJobEntity?.unityBaseGetFileResultMethod?.apiMethodId) await executeQueryWithParameters({ data: { JobId: activeExportJob?.id } }, udpJobEntity?.unityBaseGetFileResultMethod?.apiMethodId).then((res_0) => {
			setFileResultData(res_0.data);
		}).catch((err_0) => {
			addErrorIfNotExists("fileError", "Error getting file ", "error");
		});
	}, [activeExportJob?.id, udpJobEntity?.unityBaseGetFileResultMethod?.apiMethodId]);
	const clearParameters = useCallback(() => {
		setEntity(null);
		setSearchObject(null);
		setNumRowsToExport(null);
		setActiveExportJob(null);
		setErrorList([]);
	}, []);
	const updateExportParameters = useCallback((entity_0, searchObject_0) => {
		setEntity(entity_0);
		setSearchObject(searchObject_0);
	}, []);
	const addErrorIfNotExists = (id, message, severity = "error") => {
		setErrorList((prev) => {
			if (!prev.some((error) => error.id === id)) return [...prev, {
				id,
				message,
				severity
			}];
			return prev;
		});
	};
	const initialSearchWithParams = useCallback(async () => {
		await executeQueryAdHoc({ data: {
			...searchObject,
			pageSize: 1
		} }, selectedEntity?.unityBaseSearchMethod?.apiMethodId).then((res_1) => {
			setNumRowsToExport(res_1?.data?.total);
		}).catch((err_1) => {
			addErrorIfNotExists("searchObject", "Error fetching row count", "error");
		});
	}, [searchObject, selectedEntity]);
	const createExport = useCallback(async () => {
		if (selectedEntity?.unityBaseExportMethod?.apiMethodId) {
			setExportLoading(true);
			await executeQueryWithParameters({ data: { requestBody: {
				debug: true,
				exportAcrossAssociations: false,
				exportOnAllAssociations: false,
				exportSiblings: false,
				search: searchObject
			} } }, selectedEntity?.unityBaseExportMethod?.apiMethodId).then((res_2) => {
				setActiveExportJob(res_2?.data);
				setExportLoading(false);
			}).catch((err_2) => {
				addErrorIfNotExists("exportRequest", "Error creating the export job", "error");
				setExportLoading(false);
			});
		}
	}, [searchObject, selectedEntity?.unityBaseExportMethod?.apiMethodId]);
	useEffect(() => {
		if (!entityLoading) {
			if (selectedEntity?.unityBaseSearchMethod === null) addErrorIfNotExists("search", `${getSanitizedName(entity)}'s search method must be promoted`, "error");
			else initialSearchWithParams();
			if (selectedEntity?.unityBaseExportMethod === null) addErrorIfNotExists("export", `${getSanitizedName(entity)}'s export method must be promoted`, "error");
		}
	}, [
		initialSearchWithParams,
		selectedEntity,
		entity,
		entityLoading
	]);
	useEffect(() => {
		if (entity) {
			if (udpJobEntity && !udpJobEntity?.unityBaseGetFileResultMethod?.apiMethodId) addErrorIfNotExists("fileResultGet", `UdpJob's GetFileResult must be promoted to download the file`, "warning");
			if (udpJobEntity && !udpJobEntity?.unityBaseGetMethod?.apiMethodId) addErrorIfNotExists("fileBaseGet", `UdpJob's Get method must be promoted to view job status`, "warning");
		}
	}, [entity, udpJobEntity]);
	useEffect(() => {
		let isValid = true;
		errorList?.forEach((item) => {
			if (item.severity === "error") isValid = false;
		});
		setValidSearch(isValid);
	}, [errorList]);
	useEffect(() => {
		if (!activeExportJob || activeExportJob?.statusId === 3 || activeExportJob?.statusId === 4) return;
		const intervalId = setInterval(() => {
			refetchActiveJobData();
		}, 5e3);
		return () => clearInterval(intervalId);
	}, [activeExportJob, refetchActiveJobData]);
	useEffect(() => {
		if (activeExportJob?.statusId === 3) refetchfileResultData();
	}, [activeExportJob?.statusId, refetchfileResultData]);
	return {
		updateExportParameters,
		createExport,
		entity,
		searchObject,
		fileFormat,
		numRowsToExport,
		validSearch,
		errorList,
		activeExportJob,
		exportLoading,
		handleFileDownload: useCallback(() => {
			if (fileResultData?.link) {
				const link = document.createElement("a");
				link.href = fileResultData?.link;
				link.download = "";
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);
			}
		}, [fileResultData?.link]),
		clearParameters
	};
};
//#endregion
export { useUdpExport };

//# sourceMappingURL=useUdpExport.mjs.map