import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import React, { Component } from 'react';
export const withImageLoader = Wrapped => class WithImageLoader extends Component {
  constructor(...args) {
    super(...args);
    _defineProperty(this, "state", {
      imageStatus: 'loading'
    });
    _defineProperty(this, "onLoad", () => {
      this.setState({
        imageStatus: 'complete'
      });
      const {
        onExternalImageLoaded
      } = this.props;
      if (onExternalImageLoaded && this.img) {
        onExternalImageLoaded({
          width: this.img.naturalWidth,
          height: this.img.naturalHeight
        });
      }
    });
    _defineProperty(this, "onError", () => {
      this.setState({
        imageStatus: 'error'
      });
    });
  }
  componentDidMount() {
    this.fetchImage(this.props);
  }
  componentDidUpdate(newProps) {
    if (newProps.url !== this.props.url) {
      this.setState({
        imageStatus: 'loading'
      });
      this.fetchImage(newProps);
    }
  }
  componentWillUnmount() {
    if (this.img) {
      if (!process.env.REACT_SSR) {
        // Ignored via go/ees005
        // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
        this.img.removeEventListener('load', this.onLoad);
        // Ignored via go/ees005
        // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
        this.img.removeEventListener('error', this.onError);
      }
      this.img = null;
    }
  }
  fetchImage({
    url
  }) {
    if (url) {
      if (!this.img) {
        this.img = new Image();
        if (!process.env.REACT_SSR) {
          // Ignored via go/ees005
          // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
          this.img.addEventListener('load', this.onLoad);
          // Ignored via go/ees005
          // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
          this.img.addEventListener('error', this.onError);
        }
      }
      this.img.src = url;
    }
  }
  render() {
    const {
      imageStatus
    } = this.state;
    // Ignored via go/ees005
    // eslint-disable-next-line react/jsx-props-no-spreading
    return /*#__PURE__*/React.createElement(Wrapped, _extends({}, this.props, {
      imageStatus: imageStatus
    }));
  }
};