import ImageConversion from 'image-conversion';

export const readFile = file => new Promise((resolve, reject) => {
  const fileReader = new FileReader();

  fileReader.readAsDataURL(file);

  fileReader.onload = () => {
    resolve(fileReader.result);
  };

  fileReader.onerror = (err) => {
    reject(err);
  };
});

export const compressImage = async (image) => {
  const imageType = image.split(';')[0].replace('data:', '');
  const imageLoaded = await ImageConversion.dataURLtoFile(image);
  const compressedImage = await ImageConversion.compress(imageLoaded, {
    quality: 0.8,
    type: imageType,
    width: 1000
  });
  const finalImage = await ImageConversion.filetoDataURL(compressedImage);
  return finalImage;
};

export const toImage = async (image) => {
  const response = await fetch(image, {
    mode: 'cors'
  });
  const data = await response.blob();
  const metadata = {
    type: 'image/jpeg'
  };
  return new File([data], 'file', metadata);
};
