export const resizeImage = async (
  imgUrl: string,
  newWidth: number,
  type: string = "blob"
): Promise<Blob | string> => {
  const image = new Image();

  return new Promise((resolve) => {
    image.onload = () => {
      const canvas = document.createElement("canvas");
      const ctx: any = canvas.getContext("2d");
      const width = newWidth;
      const height = (image.height / image.width) * newWidth;

      canvas.width = width;
      canvas.height = height;

      ctx.drawImage(image, 0, 0, width, height);

      if (type === "blob") {
        canvas.toBlob((blob: any) => {
          resolve(blob);
        }, "image/jpeg");
      } else if (type === "base64") {
        resolve(canvas.toDataURL());
      }
    };

    image.src = imgUrl;
  });
};

export const getImageData = (
  file: File
): Promise<{
  src: string;
  width: number;
  height: number;
}> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    const image = new Image();

    reader.onload = (e: any) => {
      image.src = e.target.result as string;
    };

    reader.onerror = (e: any) => {
      return reject(e);
    };

    image.onerror = (e: any) => {
      return reject(e);
    };

    image.onload = () => {
      return resolve({
        src: image.src,
        height: image.height,
        width: image.width,
      });
    };

    reader.readAsDataURL(file);
  });
};
