// Глобальная функция для проекта, для загрузки файлов
import request from './request';
import { Method } from 'axios';

function FileDownload(
  data: string | ArrayBuffer | ArrayBufferView | Blob,
  filename: string,
): void {
  const blobData = [data];
  const blob = new Blob(blobData, { type: 'application/octet-stream' });

  const blobURL =
    window.URL && window.URL.createObjectURL
      ? window.URL.createObjectURL(blob)
      : window.webkitURL.createObjectURL(blob);

  const tempLink = document.createElement('a');
  tempLink.style.display = 'none';
  tempLink.href = blobURL;
  tempLink.setAttribute('download', filename);

  if (typeof tempLink.download === 'undefined') {
    tempLink.setAttribute('target', '_blank');
  }

  document.body.appendChild(tempLink);
  tempLink.click();

  setTimeout(function () {
    document.body.removeChild(tempLink);
    window.URL.revokeObjectURL(blobURL);
  }, 200);
}

export default FileDownload;

const DownloadFile = async (
  url: string,
  method: Method = 'GET',
  data?: never,
): Promise<void> => {
  await request({
    method,
    url,
    responseType: 'blob',
    data,
  }).then((response) => {
    const regexp = /"(.*?)"/;
    const filename =
      response.headers?.['content-disposition'].match(regexp)?.[1] ||
      'filename';
    FileDownload(response.data, filename);
  });
};

export { DownloadFile };
