import { tinyImage, getCdnUrl } from 't-comm/es/image/image';
import { composeUrlQuery } from 't-comm/es/url/url';
import React, { Component } from 'preact';


interface LazyImageProps {
  src: string;
  width?: number;
  height?: number;
  [k: string]: any;
  errorSrc?: string;
  tryTimes?: number;
}

function cdnParseImage({ src, width, height }) {
  if (!src) return src;

  return (width || height) ? tinyImage(src, width, height) : getCdnUrl(src);
}


class CdnImage extends Component<LazyImageProps, {}> {
  state = {
    showImage: '',
    haveTriedTimes: 0,
  };

  constructor(props) {
    super(props);
    const { src, width, height  } = props;

    this.state = {
      showImage: cdnParseImage({ src, width, height }),
      haveTriedTimes: 0,
    };
  }

  // eslint-disable-next-line react/no-deprecated
  componentWillReceiveProps(nextProps: Readonly<LazyImageProps>): void {
    const { src, width, height } = nextProps || {};
    if (src !== this.props.src) {
      this.setState({
        showImage: cdnParseImage({ src, width, height }),
        haveTriedTimes: 0,
      });
    }
  }

  onImgError = () => {
    const { errorSrc, tryTimes } = this.props;
    const { haveTriedTimes, showImage } = this.state;
    console.log('[onImgError]', showImage, errorSrc, tryTimes, haveTriedTimes);

    if (tryTimes && haveTriedTimes < tryTimes) {
      this.setState({
        showImage: composeUrlQuery(haveTriedTimes === 0
          ? showImage.replace('https://', 'http://')
          : showImage, { t: Date.now() }),
        haveTriedTimes: haveTriedTimes + 1,
      });
      return;
    }

    if (!errorSrc) return;
    if (showImage === errorSrc) return;

    this.setState({
      showImage: errorSrc,
    });
  };

  render() {
    return (
      // eslint-disable-next-line light/no-direct-img-src
      <img
        {...this.props}
        src={this.state.showImage}
        onError={this.onImgError}
      />

    );
  }
}

export default CdnImage;
