import * as React from 'react'
import { isSupportWebp } from 'nw-detect';

import { formatImageSize } from '../../../utils/format'


interface Props {
  src: string;
  defaultImg?: string;
  width: number;
  height: number;
  className?: string;
}

class Image extends React.Component<Props> {

  state = {
    error: false
  }

  handleError = () => {
    this.setState({
      error: true
    })
  }

  public render() {
    const {
      src,
      defaultImg,
      width,
      height,
      className
    } = this.props
    const {
      error
    } = this.state
    return (
      <>
        {
          defaultImg
            ? (
              <img
                className={className}
                src={error ? defaultImg : formatImageSize(src, width, height, isSupportWebp() ? 'webp' : 'jpg')}
                onError={this.handleError}
                alt="img"
              />
            )
            : (
              <>
                {
                  !error
                    ? (
                      <img
                        className={className}
                        src={error ? defaultImg : formatImageSize(src, width, height, isSupportWebp() ? 'webp' : 'jpg')}
                        onError={this.handleError}
                        alt="img"
                      />
                    )
                    : (
                      <span
                        className={className}
                        style={{ display: 'inline-block' }}
                      />
                    )
                }
              </>
            )
        }
      </>
    )
  }
}

export default React.memo(Image)
