import Axios from 'axios';
import { Notificator } from "../modules";
import { REPORT } from "../constants";
export default function downloadFile({ fetchUrl, setDisabled, fileName, type, sendData, }) {
    if (setDisabled) {
        setDisabled(true);
    }
    const axiosConfig = {
        method: 'GET',
        url: fetchUrl,
        responseType: 'blob',
    };
    if (sendData) {
        axiosConfig.method = 'POST';
        axiosConfig.data = sendData;
    }
    Axios(axiosConfig)
        .then(({ data }) => {
        const url = window.URL.createObjectURL(new Blob([data]));
        const a = document.createElement('a');
        a.setAttribute('download', `${fileName}`);
        // Detect Safari
        const ua = window.navigator.userAgent;
        const chromeAgent = ua.indexOf('Chrome') > -1;
        let safariAgent = ua.indexOf('Safari') > -1;
        if (chromeAgent && safariAgent)
            safariAgent = false;
        a.href = url;
        safariAgent ? (a.download = type) : (a.target = '_blank');
        document.body.appendChild(a);
        a.click();
        a.remove();
    })
        .catch((response) => {
        if (response.status === REPORT.ERROR_STATUS.NOT_ACCEPTABLE.code) {
            Notificator.success('Идет создание отчета, нажмите кнопку обновить');
        }
        else {
            Notificator.error('Ошибка загрузки файла!');
        }
    })
        .finally(() => setDisabled && setDisabled(false));
}
