import axios from 'axios';

export async function upload(
  blob: Blob,
  shared = false,
  filename = 'thumb.png',
  directory = '/2D/缩略图'
) {
  const form = new FormData();
  form.append('filename', filename);
  form.append('directory', directory);
  form.append('public', shared + '');
  form.append('file', blob);
  const ret: any = await axios.post('/api/image/upload', form);
  if (!ret) {
    return;
  }

  return ret;
}

export async function delImage(image: string) {
  const ret: any = await axios.delete('/api' + image);
  if (ret.error) {
    return false;
  }

  return true;
}

export async function addImage(image: string) {
  const ret: any = await axios.post('/api/user/image', { image });
  if (ret.error) {
    return '';
  }

  return ret.id;
}

export function filename(str: string) {
  const i = str.lastIndexOf('.');
  return str.substring(0, i);
}

const units = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
export function formatBytes(size: number) {
  let l = 0;
  let n = size / 1024;

  while (n >= 1024 && ++l) {
    n = n / 1024;
  }

  return Math.round(n * 100) / 100 + ' ' + units[l];
}

/**
 * 读取文件内容，返回字符串
 * @param file 文件
 */
export async function readFile(file: Blob) {
  return new Promise<string>((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      resolve(reader.result as string);
    };
    reader.onerror = reject;
    // readAsText 使 result 一定是字符串
    reader.readAsText(file);
  });
}

export function dataURLtoBlob(base64: string) {
  let arr: any = base64.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

/**
 * 图片转 Blob
 * @param img 图片
 */
export function saveToBlob(img: HTMLImageElement): Blob {
  const canvas: HTMLCanvasElement = document.createElement('canvas');
  canvas.setAttribute('origin-clean', 'false');
  canvas.width = img.width;
  canvas.height = img.height;

  const context: any = canvas.getContext('2d');
  context.filter = window.getComputedStyle(img).filter;
  context.drawImage(img, 0, 0, canvas.width, canvas.height);
  return dataURLtoBlob(canvas.toDataURL());
}
