import { apiMutate } from "../../utilities";
import ConfigService from "../../configService";
const BASE = ConfigService.productV1ApiUrl;
export const downloadAttachment = async (iD, fileName, handleErrorSnackbar, setAttachmentProgress) => {
    try {
        setAttachmentProgress(false);
        const response = await apiMutate(BASE, `DownloadAttachment/${iD}/Download`, {
            method: 'get',
            responseType: 'blob', // 👈 tell Axios to expect binary
        });
        // Create blob and download link
        const blob = new Blob([response.data], { type: 'application/pdf' });
        const url = window.URL.createObjectURL(blob);
        const cleanName = cleanFileName(fileName);
        const link = document.createElement('a');
        link.href = url;
        link.download = cleanName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        setAttachmentProgress(true);
    }
    catch (error) {
        setAttachmentProgress(true);
        handleErrorSnackbar(``, "Download failed:", error);
    }
};
export const downloadAttachmentByBlobUrl = async (url, fileName, handleErrorSnackbar, setAttachmentProgress) => {
    try {
        setAttachmentProgress(false);
        const cleanName = cleanFileName(fileName);
        const link = document.createElement('a');
        link.href = url;
        link.download = cleanName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        setAttachmentProgress(true);
    }
    catch (error) {
        setAttachmentProgress(true);
        handleErrorSnackbar(``, "Download failed:", error);
    }
};
function cleanFileName(fileName) {
    // Match GUID suffix preceded by underscore
    const guidRegex = /_[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
    if (!guidRegex.test(fileName)) {
        return fileName; // no GUID, return as is
    }
    // Remove GUID suffix
    let nameWithoutGuid = fileName.replace(guidRegex, '');
    // Now, check for repeated extension pattern at the end: e.g. `.png.png`
    const repeatedExtRegex = /(\.[^.]+)\1$/; // matches any repeated extension like '.png.png'
    if (repeatedExtRegex.test(nameWithoutGuid)) {
        // Remove one repeated extension
        nameWithoutGuid = nameWithoutGuid.replace(repeatedExtRegex, '$1');
    }
    return nameWithoutGuid;
}
export const createBlobUrl = async (iD) => {
    const response = await apiMutate(BASE, `DownloadAttachment/${iD}/Download`, {
        method: 'get',
        responseType: 'blob', // 👈 tell Axios to expect binary
    });
    // Create blob and download link
    const blob = new Blob([response.data], { type: 'application/pdf' });
    const url = window.URL.createObjectURL(blob);
    return url;
};
//# sourceMappingURL=downloadAttachmentFiles.js.map