'use strict';

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

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

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

const propTypes = {
  location: _propTypes2.default.object,
  match: _propTypes2.default.object,
  readContent: _propTypes2.default.func.isRequired,
  renderError: _propTypes2.default.func,
  renderLoading: _propTypes2.default.func
}; /* global URL */

class ContentViewerPage extends _react.Component {
  constructor() {
    super();

    this.state = {
      blobUrl: null
    };
  }

  componentDidMount() {
    this.readContent();
  }

  componentDidUpdate(prevProps) {
    const contentPath = (0, _get2.default)(this.props.match, ['params', 'contentPath']);
    const prevContentPath = (0, _get2.default)(prevProps.match, ['params', 'contentPath']);

    if (contentPath !== prevContentPath) {
      this.reset();
      this.readContent();
    }
  }

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

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


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

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

  readContent() {
    var _props = this.props;
    const location = _props.location,
          match = _props.match,
          readContent = _props.readContent;


    readContent(location, match).then(response => {
      if (response && response.status === 200 && response.data && !this.isUnmounted) {
        this.setState({
          blobUrl: URL.createObjectURL(response.data)
        });
      }
    }).catch(error => {
      this.setState({
        error
      });
    });
  }

  render() {
    var _props2 = this.props;
    const renderError = _props2.renderError,
          renderLoading = _props2.renderLoading;
    var _state = this.state;
    const blobUrl = _state.blobUrl,
          error = _state.error;


    if (error) {
      return renderError ? renderError(error) : null;
    }

    if (!blobUrl) {
      return renderLoading ? renderLoading() : null;
    }

    const style = {
      position: 'fixed',
      left: '0',
      top: '0',
      width: '100%',
      height: '100%',
      border: 'none'
    };

    return _react2.default.createElement('iframe', { src: blobUrl, style: style });
  }
}

exports.default = ContentViewerPage;
ContentViewerPage.propTypes = propTypes;