import {
  ViaLinkSaverConfig,
  BlobCreatorConfig,
  BlobSaverConfig,
} from '@interfaces/utils/files';
import FileSaver from 'file-saver';

export function saveFileViaLink({
  anchor,
  blob = null,
  hrefData = '',
  fileName = '',
  target = '',
}: ViaLinkSaverConfig): void {
  try {
    let urlToDownload = '';
    if (blob) {
      urlToDownload = window.URL.createObjectURL(blob);
      anchor.href = urlToDownload;
    } else if (hrefData) {
      anchor.href = hrefData;
    }
    if (fileName) {
      anchor.download = fileName;
    }
    if (target) {
      anchor.target = target;
    }
    anchor.click();
    anchor.removeAttribute('href');
    anchor.removeAttribute('download');
    if (blob) {
      window.URL.revokeObjectURL(urlToDownload);
    }
  } catch (e) {
    console.error(`['utils/files/saveFileViaLink] - ${e.toString()}`);
  }
}

export function saveBlob({
  blob,
  binary,
  fileName = 'print.pdf',
  blobType = 'application/pdf',
}: BlobSaverConfig): Blob | null | void {
  FileSaver.saveAs(blob || createBlob({ binary, blobType }), fileName);
}

export function createBlob({
  binary,
  blobType = 'application/pdf',
}: BlobCreatorConfig): Blob | string {
  try {
    return new Blob([`${binary}`], {
      type: blobType,
    });
  } catch (e) {
    console.error(`[utils/files/createBlob] - ${e.toString()}`);
    return '';
  }
}

/**
 *
 * Функция конертации названия в читаемый вид с расширением
 *
 * @param {File} file
 * @returns string
 */
export function extractFileName(file?: File): string {
  if (!file) return '';
  const [, name, ext] = file.name.match(/^(.*)\.([0-9a-z]+)$/i) || [];
  return `${name}.${ext?.toLowerCase()}`;
}
