// @flow
import * as React from 'react'
import defaults, { type ImageType } from '../../types/Image.flow'

import getImageUrl from '../../utils/getImageUrl'
import getSrc from '../../utils/getSrc'
import { ImageConsumer } from '../ImageContext'

type Props = ImageType & {
  style?: {},
  tag?: React.Node | string,
}

function ImageBox({
  style = {},
  blur,
  flip,
  scaleMode,
  progressive,
  quality,
  rotate,
  output: outputOmmit,
  height,
  width,
  src,
  tag,
  ...props
}: Props) {
  return (
    <ImageConsumer>
      {({
        microserviceUrl,
        output,
        resolvedOutput,
        baseImgBoxComponent,
        baseUrl,
      }) => {
        const Component = tag || baseImgBoxComponent
        if (!resolvedOutput) return null
        const imgProps = {
          blur,
          flip,
          scaleMode,
          progressive,
          quality,
          rotate,
          output,
          height,
          width,
          src: getSrc(src, baseUrl),
        }
        const newStyle = {
          ...style,
          backgroundImage: `url(${getImageUrl(microserviceUrl, imgProps)})`,
        }
        return <Component style={newStyle} {...props} />
      }}
    </ImageConsumer>
  )
}

ImageBox.defaultProps = defaults

export default ImageBox
