'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _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; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

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

var _Image2 = _interopRequireDefault(_Image);

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } /* global window, URL */

const propTypes = {
  src: _propTypes2.default.string.isRequired,
  alt: _propTypes2.default.string,
  errorMessage: _propTypes2.default.node,
  pendingMessage: _propTypes2.default.node,
  retry: _propTypes2.default.bool,
  retryLimit: _propTypes2.default.number,
  readImage: _propTypes2.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.blobUrl;


    if (blobUrl) {
      URL.revokeObjectURL(blobUrl);

      this.setState({
        blobUrl: null
      });
    }

    if (this.retryTimer) {
      window.clearTimeout(this.retryTimer);

      this.retryTimer = null;
    }
  }

  tryReadImage(retriesRemaining) {
    var _props = this.props;
    const src = _props.src,
          retryLimit = _props.retryLimit,
          readImage = _props.readImage;


    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, _get2.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() {
    var _props2 = this.props;
    const retry = _props2.retry,
          retryLimit = _props2.retryLimit;


    const retriesRemaining = retry ? retryLimit : 0;

    this.tryReadImage(retriesRemaining);
  }

  render() {
    var _props3 = this.props;

    const alt = _props3.alt,
          errorMessage = _props3.errorMessage,
          pendingMessage = _props3.pendingMessage,
          src = _props3.src,
          retry = _props3.retry,
          retryLimit = _props3.retryLimit,
          readImage = _props3.readImage,
          remainingProps = _objectWithoutProperties(_props3, ['alt', 'errorMessage', 'pendingMessage', 'src', 'retry', 'retryLimit', 'readImage']);

    var _state = this.state;
    const blobUrl = _state.blobUrl,
          isError = _state.isError;


    if (isError) {
      return _react2.default.createElement(
        'div',
        { className: _Image2.default.error },
        errorMessage
      );
    }

    if (blobUrl) {
      return _react2.default.createElement('img', _extends({ className: _Image2.default.normal, src: blobUrl, alt: alt }, remainingProps));
    }

    return _react2.default.createElement(
      'div',
      { className: _Image2.default.pending },
      pendingMessage
    );
  }
}

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