import React, { memo } from 'react'
import { isBlurhashValid } from 'blurhash'
import { Blurhash } from 'react-native-blurhash'
import deepEqual from 'fast-deep-equal/es6'
import { ImageBlurhashProps } from 'types'
import { getBlurhash } from 'utils/blurhash'

const ImageBlurhash = ({
  object,
  source,
  componentProps,
  layout,
}: ImageBlurhashProps) => {
  if (!layout) {
    return null
  }

  const blurhash = getBlurhash(object, source, componentProps)

  if (!blurhash) {
    return null
  }

  const { blurHash } = blurhash

  const validityCheck = isBlurhashValid(blurHash)
  if (validityCheck.result === false) {
    return null
  }

  const { blurHashWidth, blurHashHeight, resizeMode } = blurhash

  return (
    <Blurhash
      blurhash={blurHash}
      decodeWidth={blurHashWidth}
      decodeHeight={blurHashHeight}
      resizeMode={resizeMode}
      style={{ width: layout.width, height: layout.height }}
    />
  )
}

export default memo(ImageBlurhash, deepEqual)
