export function isImageType(type: string): boolean {
  return type.match(/^image\//) !== null;
}

export function decodeAsImage(file: File): Promise<HTMLImageElement> {
  return new Promise<HTMLImageElement>((resolve, reject) => {
    if (file.size > 20 * 1000 * 1000) {
      reject(new Error("File too large to decode"));
    } else if (typeof FileReader === "undefined") {
      reject(new Error("FileReader not supported"));
    } else if (typeof Image === "undefined") {
      reject(new Error("Image not supported"));
    } else {
      const fileReader = new FileReader();
      const image = new Image();
      image.onerror = reject;
      image.onload = () => {
        resolve(image);
      };
      fileReader.onerror = reject;
      fileReader.onload = () => {
        image.src = fileReader.result as string;
      };
      fileReader.readAsDataURL(file);
    }
  });
}

const CHROME_PASTED_IMAGE_NAME = "image.png";

export function pixelRatio(image: Pick<File, "type" | "name">, viaPaste: boolean) {
  const devicePixelRatio = typeof window !== "undefined" ? window.devicePixelRatio : 1;
  return image.name.match(/@2x\./) !== null ? 2 : viaPaste && image.name === CHROME_PASTED_IMAGE_NAME ? devicePixelRatio : 1;
}
