import { useCallback, useEffect, useState } from 'react';
import { executeQueryAdHoc } from '../utilities/methodUtils';
import { executeQueryWithParameters } from '../utilities/methodUtils';
import { usePromotedMethodEntity } from '../../hooks/usePromotedMethodEntity';
import { getSanitizedName } from '../../utilities/entities/entityUtilities';
export const useUdpExport = (apiCatalogId, productId) => {
    var _a, _b, _c;
    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 () => {
        var _a, _b;
        if ((_a = udpJobEntity === null || udpJobEntity === void 0 ? void 0 : udpJobEntity.unityBaseGetMethod) === null || _a === void 0 ? void 0 : _a.apiMethodId) {
            await executeQueryWithParameters({
                data: { id: activeExportJob === null || activeExportJob === void 0 ? void 0 : activeExportJob.id }
            }, (_b = udpJobEntity === null || udpJobEntity === void 0 ? void 0 : udpJobEntity.unityBaseGetMethod) === null || _b === void 0 ? void 0 : _b.apiMethodId)
                .then((res) => {
                setActiveExportJob(res.data);
            })
                .catch((err) => {
                addErrorIfNotExists('jobstatus', 'Error getting job status ', 'error');
            });
        }
    }, [activeExportJob === null || activeExportJob === void 0 ? void 0 : activeExportJob.id, (_a = udpJobEntity === null || udpJobEntity === void 0 ? void 0 : udpJobEntity.unityBaseGetMethod) === null || _a === void 0 ? void 0 : _a.apiMethodId]);
    const refetchfileResultData = useCallback(async () => {
        var _a, _b;
        if ((_a = udpJobEntity === null || udpJobEntity === void 0 ? void 0 : udpJobEntity.unityBaseGetFileResultMethod) === null || _a === void 0 ? void 0 : _a.apiMethodId) {
            await executeQueryWithParameters({
                data: { JobId: activeExportJob === null || activeExportJob === void 0 ? void 0 : activeExportJob.id }
            }, (_b = udpJobEntity === null || udpJobEntity === void 0 ? void 0 : udpJobEntity.unityBaseGetFileResultMethod) === null || _b === void 0 ? void 0 : _b.apiMethodId)
                .then((res) => {
                setFileResultData(res.data);
            })
                .catch((err) => {
                addErrorIfNotExists('fileError', 'Error getting file ', 'error');
            });
        }
    }, [
        activeExportJob === null || activeExportJob === void 0 ? void 0 : activeExportJob.id,
        (_b = udpJobEntity === null || udpJobEntity === void 0 ? void 0 : udpJobEntity.unityBaseGetFileResultMethod) === null || _b === void 0 ? void 0 : _b.apiMethodId
    ]);
    const clearParameters = useCallback(() => {
        setEntity(null);
        setSearchObject(null);
        setNumRowsToExport(null);
        setActiveExportJob(null);
        setErrorList([]);
    }, []);
    const updateExportParameters = useCallback((entity, searchObject) => {
        setEntity(entity);
        setSearchObject(searchObject);
    }, []);
    const addErrorIfNotExists = (id, message, severity = 'error') => {
        setErrorList((prev) => {
            const exists = prev.some((error) => error.id === id);
            if (!exists) {
                return [...prev, { id, message, severity }];
            }
            return prev;
        });
    };
    const initialSearchWithParams = useCallback(async () => {
        var _a;
        await executeQueryAdHoc({
            data: Object.assign(Object.assign({}, searchObject), { pageSize: 1 })
        }, (_a = selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseSearchMethod) === null || _a === void 0 ? void 0 : _a.apiMethodId)
            .then((res) => {
            var _a;
            setNumRowsToExport((_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.total);
        })
            .catch((err) => {
            addErrorIfNotExists('searchObject', 'Error fetching row count', 'error');
        });
    }, [searchObject, selectedEntity]);
    const createExport = useCallback(async () => {
        var _a, _b;
        if ((_a = selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseExportMethod) === null || _a === void 0 ? void 0 : _a.apiMethodId) {
            setExportLoading(true);
            await executeQueryWithParameters({
                data: {
                    requestBody: {
                        debug: true,
                        exportAcrossAssociations: false,
                        exportOnAllAssociations: false,
                        exportSiblings: false,
                        search: searchObject
                    }
                }
            }, (_b = selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseExportMethod) === null || _b === void 0 ? void 0 : _b.apiMethodId)
                .then((res) => {
                setActiveExportJob(res === null || res === void 0 ? void 0 : res.data);
                setExportLoading(false);
            })
                .catch((err) => {
                addErrorIfNotExists('exportRequest', 'Error creating the export job', 'error');
                setExportLoading(false);
            });
        }
    }, [searchObject, (_c = selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseExportMethod) === null || _c === void 0 ? void 0 : _c.apiMethodId]);
    useEffect(() => {
        if (!entityLoading) {
            if ((selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseSearchMethod) === null) {
                addErrorIfNotExists('search', `${getSanitizedName(entity)}'s search method must be promoted`, 'error');
            }
            else {
                initialSearchWithParams();
            }
            if ((selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseExportMethod) === null) {
                addErrorIfNotExists('export', `${getSanitizedName(entity)}'s export method must be promoted`, 'error');
            }
        }
    }, [initialSearchWithParams, selectedEntity, entity, entityLoading]);
    useEffect(() => {
        var _a, _b;
        if (entity) {
            if (udpJobEntity &&
                !((_a = udpJobEntity === null || udpJobEntity === void 0 ? void 0 : udpJobEntity.unityBaseGetFileResultMethod) === null || _a === void 0 ? void 0 : _a.apiMethodId)) {
                addErrorIfNotExists('fileResultGet', `UdpJob's GetFileResult must be promoted to download the file`, 'warning');
            }
            if (udpJobEntity && !((_b = udpJobEntity === null || udpJobEntity === void 0 ? void 0 : udpJobEntity.unityBaseGetMethod) === null || _b === void 0 ? void 0 : _b.apiMethodId)) {
                addErrorIfNotExists('fileBaseGet', `UdpJob's Get method must be promoted to view job status`, 'warning');
            }
        }
    }, [entity, udpJobEntity]);
    useEffect(() => {
        let isValid = true;
        errorList === null || errorList === void 0 ? void 0 : errorList.forEach((item) => {
            if (item.severity === 'error') {
                isValid = false;
            }
        });
        setValidSearch(isValid);
    }, [errorList]);
    useEffect(() => {
        if (!activeExportJob ||
            (activeExportJob === null || activeExportJob === void 0 ? void 0 : activeExportJob.statusId) === 3 ||
            (activeExportJob === null || activeExportJob === void 0 ? void 0 : activeExportJob.statusId) === 4)
            return;
        const intervalId = setInterval(() => {
            refetchActiveJobData();
        }, 5000);
        return () => clearInterval(intervalId);
    }, [activeExportJob, refetchActiveJobData]);
    useEffect(() => {
        if ((activeExportJob === null || activeExportJob === void 0 ? void 0 : activeExportJob.statusId) === 3) {
            refetchfileResultData();
        }
    }, [activeExportJob === null || activeExportJob === void 0 ? void 0 : activeExportJob.statusId, refetchfileResultData]);
    const handleFileDownload = useCallback(() => {
        if (fileResultData === null || fileResultData === void 0 ? void 0 : fileResultData.link) {
            const link = document.createElement('a');
            link.href = fileResultData === null || fileResultData === void 0 ? void 0 : fileResultData.link;
            link.download = '';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }, [fileResultData === null || fileResultData === void 0 ? void 0 : fileResultData.link]);
    return {
        updateExportParameters,
        createExport,
        entity,
        searchObject,
        fileFormat,
        numRowsToExport,
        validSearch,
        errorList,
        activeExportJob,
        exportLoading,
        handleFileDownload,
        clearParameters
    };
};
//# sourceMappingURL=useUdpExport.js.map