'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 _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* global window, URL */

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

var defaultProps = {
  errorMessage: '',
  pendingMessage: '',
  retry: false,
  retryLimit: 5
};

/**
 * A replacement for img that gets images from the CollectionSpace REST API using token auth.
 */

var Image = function (_Component) {
  _inherits(Image, _Component);

  function Image(props) {
    _classCallCheck(this, Image);

    var _this = _possibleConstructorReturn(this, (Image.__proto__ || Object.getPrototypeOf(Image)).call(this, props));

    _this.state = {
      blobUrl: null
    };
    return _this;
  }

  _createClass(Image, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.readImage();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      if (this.props.src !== prevProps.src) {
        this.reset();
        this.readImage();
      }
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      this.reset();
      this.isUnmounted = true;
    }
  }, {
    key: 'reset',
    value: function reset() {
      var blobUrl = this.state.blobUrl;


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

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

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

        this.retryTimer = null;
      }
    }
  }, {
    key: 'tryReadImage',
    value: function tryReadImage(retriesRemaining) {
      var _this2 = this;

      var _props = this.props,
          src = _props.src,
          retryLimit = _props.retryLimit,
          readImage = _props.readImage;


      readImage(src).then(function (response) {
        if (response.status === 200 && response.data && !_this2.isUnmounted) {
          _this2.setState({
            blobUrl: URL.createObjectURL(response.data)
          });
        }
      }).catch(function (error) {
        if (!_this2.isUnmounted) {
          if ((0, _get2.default)(error, ['response', 'status']) === 404 && retriesRemaining > 0) {
            // Make retries back off exponentially.

            var pauseTime = Math.pow(2, retryLimit - retriesRemaining) * 1000;

            _this2.retryTimer = window.setTimeout(function () {
              _this2.tryReadImage(retriesRemaining - 1);
            }, pauseTime);
          } else {
            _this2.setState({
              isError: true
            });
          }
        }
      });
    }
  }, {
    key: 'readImage',
    value: function readImage() {
      var _props2 = this.props,
          retry = _props2.retry,
          retryLimit = _props2.retryLimit;


      var retriesRemaining = retry ? retryLimit : 0;

      this.tryReadImage(retriesRemaining);
    }
  }, {
    key: 'render',
    value: function render() {
      var _props3 = this.props,
          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,
          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
      );
    }
  }]);

  return Image;
}(_react.Component);

exports.default = Image;


Image.propTypes = propTypes;
Image.defaultProps = defaultProps;