import {ImageManipulator, SaveFormat} from 'expo-image-manipulator'

type ImageInput = {uri: string; width?: number; height?: number}

// react-native streams file:// uris reliably through xhr
export const readAsBlob = (uri: string): Promise<Blob> =>
  new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.onload = () => resolve(xhr.response)
    xhr.onerror = () => reject(new Error('failed to read image'))
    xhr.responseType = 'blob'
    xhr.open('GET', uri, true)
    xhr.send(null)
  })

// downscale to a max edge and re-encode as jpeg (re-encoding drops exif)
export const downscaleJpeg = async (
  {uri, width, height}: ImageInput,
  {maxEdge, base64 = false}: {maxEdge: number; base64?: boolean},
) => {
  const ctx = ImageManipulator.manipulate(uri)
  const longest = Math.max(width ?? 0, height ?? 0)
  if (longest > maxEdge && width && height) {
    ctx.resize({width: Math.round(width * (maxEdge / longest))})
  }
  const rendered = await ctx.renderAsync()
  return rendered.saveAsync({
    format: SaveFormat.JPEG,
    compress: 0.8,
    base64,
  })
}
