export function fileToBase64(file: Blob): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      resolve(reader.result as string);
    };
    reader.onerror = () => {
      reject(new Error('Error converting file to base64'));
    };
  });
}

export function base64ToFile(base64String: string, filename?: string): Promise<File> {
  return new Promise((resolve, reject) => {
    const arr = base64String.split(',');
    // eslint-disable-next-line prefer-named-capture-group
    const type = arr[0].match(/:(.*?);/)![1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }

    const file = new File([u8arr], filename || 'file', { type });
    resolve(file);
  });
}
