"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _get = _interopRequireDefault(require("lodash/get"));

var _Image = _interopRequireDefault(require("../../../styles/cspace-ui/Image.css"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

const propTypes = {
  src: _propTypes.default.string.isRequired,
  alt: _propTypes.default.string,
  errorMessage: _propTypes.default.node,
  pendingMessage: _propTypes.default.node,
  retry: _propTypes.default.bool,
  retryLimit: _propTypes.default.number,
  readImage: _propTypes.default.func.isRequired
};
const defaultProps = {
  errorMessage: '',
  pendingMessage: '',
  retry: false,
  retryLimit: 5
};
/**
 * A replacement for img that gets images from the CollectionSpace REST API using token auth.
 */

class Image extends _react.Component {
  constructor(props) {
    super(props);
    this.state = {
      blobUrl: null
    };
  }

  componentDidMount() {
    this.readImage();
  }

  componentDidUpdate(prevProps) {
    if (this.props.src !== prevProps.src) {
      this.reset();
      this.readImage();
    }
  }

  componentWillUnmount() {
    this.reset();
    this.isUnmounted = true;
  }

  reset() {
    const {
      blobUrl
    } = this.state;

    if (blobUrl) {
      URL.revokeObjectURL(blobUrl);
      this.setState({
        blobUrl: null
      });
    }

    if (this.retryTimer) {
      window.clearTimeout(this.retryTimer);
      this.retryTimer = null;
    }
  }

  tryReadImage(retriesRemaining) {
    const {
      src,
      retryLimit,
      readImage
    } = this.props;
    readImage(src).then(response => {
      if (response.status === 200 && response.data && !this.isUnmounted) {
        this.setState({
          blobUrl: URL.createObjectURL(response.data)
        });
      }
    }).catch(error => {
      if (!this.isUnmounted) {
        if ((0, _get.default)(error, ['response', 'status']) === 404 && retriesRemaining > 0) {
          // Make retries back off exponentially.
          const pauseTime = Math.pow(2, retryLimit - retriesRemaining) * 1000;
          this.retryTimer = window.setTimeout(() => {
            this.tryReadImage(retriesRemaining - 1);
          }, pauseTime);
        } else {
          this.setState({
            isError: true
          });
        }
      }
    });
  }

  readImage() {
    const {
      retry,
      retryLimit
    } = this.props;
    const retriesRemaining = retry ? retryLimit : 0;
    this.tryReadImage(retriesRemaining);
  }

  render() {
    const _this$props = this.props,
          {
      alt,
      errorMessage,
      pendingMessage,

      /* eslint-disable no-unused-vars */
      src,
      retry,
      retryLimit,
      readImage
    } = _this$props,
          remainingProps = _objectWithoutProperties(_this$props, ["alt", "errorMessage", "pendingMessage", "src", "retry", "retryLimit", "readImage"]);

    const {
      blobUrl,
      isError
    } = this.state;

    if (isError) {
      return _react.default.createElement("div", {
        className: _Image.default.error
      }, errorMessage);
    }

    if (blobUrl) {
      return _react.default.createElement("img", _extends({
        className: _Image.default.normal,
        src: blobUrl,
        alt: alt
      }, remainingProps));
    }

    return _react.default.createElement("div", {
      className: _Image.default.pending
    }, pendingMessage);
  }

}

exports.default = Image;
Image.propTypes = propTypes;
Image.defaultProps = defaultProps;