'use strict';

exports.__esModule = true;

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactAriaModal = require('react-aria-modal');

var _reactAriaModal2 = _interopRequireDefault(_reactAriaModal);

var _ = require('./..');

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

var _ref = _react2.default.createElement(_.Icon, { className: 'cui-lightbox__thumbnail--icon', name: 'secure_28' });

var _ref3 = _react2.default.createElement(_.Icon, { name: 'arrow-right_16' });

var _ref4 = _react2.default.createElement(_.Icon, { name: 'arrow-right_16' });

var _ref5 = _react2.default.createElement(_.Icon, { name: 'download_16' });

var _ref6 = _react2.default.createElement(_.Icon, { name: 'arrow-right_16' });

var _ref7 = _react2.default.createElement(_.Icon, { name: 'arrow-right_16' });

var _ref8 = _react2.default.createElement(_.Icon, { name: 'zoom-out_16' });

var _ref9 = _react2.default.createElement(_.Icon, { name: 'zoom-in_16' });

var _ref10 = _react2.default.createElement(
  'div',
  { className: 'cui-lightbox__control cui-lightbox__control-spinner' },
  _react2.default.createElement(_.Spinner, { size: 28 })
);

var _ref11 = _react2.default.createElement(_.Icon, { name: 'cancel_16' });

var _ref13 = _react2.default.createElement(_.Spinner, { className: 'cui-lightbox__decrypting-spinner' });

var Lightbox = function (_React$Component) {
  (0, _inherits3.default)(Lightbox, _React$Component);

  function Lightbox() {
    var _temp, _this, _ret;

    (0, _classCallCheck3.default)(this, Lightbox);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {
      viewportDimensions: {
        width: 600,
        height: 600
      },
      zoom: 1
    }, _this.handleResize = function () {
      var _this2 = _this,
          viewport = _this2.viewport;

      _this.setState({
        viewportDimensions: {
          width: viewport.offsetWidth,
          height: viewport.offsetHeight
        }
      });
    }, _this.handleKeyDown = function (e) {
      var _this$props = _this.props,
          index = _this$props.index,
          pages = _this$props.pages;

      var newIndex = void 0;

      switch (e.keyCode) {
        // Escape
        case 27:
          _this.handleClose();
          return;
        // left arrow & up arrow
        case 37:
        case 38:
          newIndex = Math.max(index - 1, 0);
          break;
        // right arrow & down arrow
        case 39:
        case 40:
          newIndex = Math.min(index + 1, pages.length - 1);
          break;
        // page up & home
        case 33:
        case 36:
          newIndex = 0;
          break;
        // page down & end
        case 34:
        case 35:
          newIndex = pages.length - 1;
          break;
        // 1 - 9
        case 49:
        case 50:
        case 51:
        case 52:
        case 53:
        case 54:
        case 55:
        case 56:
        case 57:
          newIndex = Math.min(e.keyCode - 49, pages.length - 1);
          break;
        default:
          return;
      }
      _this.triggerPageChange(newIndex, e);
    }, _this.handleThumbnailClick = function (index) {
      var onChange = _this.props.onChange;

      onChange && onChange(index);
    }, _this.triggerPageChange = function (index, e) {
      var _this$props2 = _this.props,
          onChange = _this$props2.onChange,
          pages = _this$props2.pages;

      var target = _this.lightBox && _this.lightBox.querySelector('[data-index=\'' + index + '\']');
      if (index >= 0 && index <= pages.length - 1) {
        onChange && onChange(index);
      }
      e.stopPropagation();
      target && target.scrollIntoViewIfNeeded();
    }, _this.stopPropagation = function (e) {
      e.stopPropagation();
    }, _this.setZoom = function (increment) {
      var newZoom = _this.state.zoom + increment;
      _this.setState({
        zoom: newZoom < 0.25 ? 0.25 : newZoom
      });
    }, _this.handleDownload = function () {
      var onDownload = _this.props.onDownload;

      onDownload && onDownload();
    }, _this.handleClose = function () {
      var onClose = _this.props.onClose;

      onClose && onClose();
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  Lightbox.prototype.componentDidMount = function componentDidMount() {
    window.addEventListener('keydown', this.handleKeyDown, true);
    window.addEventListener('resize', this.handleResize, true);
  };

  Lightbox.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    if (nextProps.index !== this.props.index && this.state.zoom > 1 && this.imgWrapper) {
      var viewportNode = this.viewport;
      viewportNode.scrollTop = 0;
      viewportNode.scrollLeft = (this.imgWrapper.offsetWidth - viewportNode.offsetWidth) / 2;
    }
  };

  Lightbox.prototype.componentWillUnmount = function componentWillUnmount() {
    window.removeEventListener('keydown', this.handleKeyDown, true);
    window.removeEventListener('resize', this.handleResize, true);
  };

  Lightbox.prototype.render = function render() {
    var _this3 = this;

    var _props = this.props,
        pages = _props.pages,
        index = _props.index,
        width = _props.width,
        height = _props.height,
        tooltips = _props.tooltips,
        downloading = _props.downloading,
        info = _props.info,
        name = _props.name,
        applicationId = _props.applicationId;
    var _state = this.state,
        zoom = _state.zoom,
        viewportDimensions = _state.viewportDimensions;

    var currentPage = pages[index];
    var showColumn = pages.length > 1;

    var calculateAspectRatioFit = function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
      var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight, 1);
      return {
        width: Math.round(srcWidth * ratio),
        height: Math.round(srcHeight * ratio)
      };
    };

    var getThumbnails = function getThumbnails() {
      var thumbnails = pages.map(function (page, idx) {
        var key = idx + ':' + page.thumb;
        var body = void 0;

        if (page.decrypting) {
          var scale = width / 150;
          var scaleY = height / scale;
          var style = {
            height: Math.round(scaleY)
          };
          key += ':decrypting';

          body = _react2.default.createElement(
            'div',
            {
              className: 'cui-lightbox__thumbnail' + ('' + (!!page.decrypting && ' cui-lightbox__thumbnail--decrypting' || '')),
              'data-index': idx,
              style: style
            },
            _ref
          );
        } else {
          body = _react2.default.createElement('img', {
            alt: '',
            className: 'cui-lightbox__thumbnail' + ('' + (!!page.decrypting && ' cui-lightbox__thumbnail--decrypting' || '')),
            'data-index': idx,
            draggable: 'false',
            onDragStart: function onDragStart() {
              return false;
            },
            src: page.thumb
          });
        }

        return _react2.default.createElement(
          'div',
          {
            className: 'cui-lightbox__thumbnail-wrapper' + ('' + (idx === index && ' cui-lightbox__thumbnail-wrapper--selected' || '')),
            key: key,
            onClick: function onClick() {
              return _this3.handleThumbnailClick(idx);
            },
            onKeyPress: function onKeyPress() {
              return _this3.handleThumbnailClick(idx);
            },
            role: 'button',
            tabIndex: '0'
          },
          body,
          _react2.default.createElement(
            'div',
            null,
            idx + 1
          )
        );
      });
      return _react2.default.createElement(
        'div',
        { className: 'cui-lightbox__list' },
        thumbnails
      );
    };

    var getViewport = function getViewport() {
      var viewport = void 0;
      var dimensions = calculateAspectRatioFit(width * zoom, height * zoom, viewportDimensions.width, viewportDimensions.height);
      var imageContainerStyles = {
        width: dimensions.width + 'px',
        height: dimensions.height + 'px'
      };

      if (currentPage.content) {
        if (currentPage.fullView) {
          imageContainerStyles = {
            width: '100%',
            height: '100%',
            overflow: 'hidden'
          };
        }
        viewport = _react2.default.createElement(
          'div',
          {
            className: 'cui-lightbox__viewport-content',
            draggable: 'false',
            onClick: _this3.stopPropagation,
            onKeyPress: _this3.stopPropagation,
            onDoubleClick: function onDoubleClick() {
              return _this3.setZoom(0.25);
            },
            onDragStart: function onDragStart() {
              return false;
            },
            role: 'button',
            tabIndex: '0'
          },
          currentPage.content
        );
      } else if (currentPage.image) {
        if (zoom <= 1) {
          /* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
          viewport = _react2.default.createElement('img', {
            alt: '',
            className: 'cui-lightbox__viewport-image',
            draggable: 'false',
            onClick: _this3.stopPropagation,
            onKeyPress: _this3.stopPropagation,
            onDoubleClick: function onDoubleClick() {
              return _this3.setZoom(0.25);
            },
            onDragStart: function onDragStart() {
              return false;
            },
            src: currentPage.image
          });
        } else {
          imageContainerStyles = {};
          viewport = _react2.default.createElement('img', {
            alt: '',
            className: 'cui-lightbox__viewport-image',
            draggable: 'false',
            onClick: _this3.stopPropagation,
            onKeyPress: _this3.stopPropagation,
            onDoubleClick: function onDoubleClick() {
              return _this3.setZoom(0.25);
            },
            onDragStart: function onDragStart() {
              return false;
            },
            src: currentPage.image,
            style: {
              maxHeight: height * zoom,
              maxWidth: width * zoom,
              minHeight: height * zoom,
              minWidth: width * zoom
            }
          });
        }
      }

      return _react2.default.createElement(
        'div',
        {
          className: 'cui-lightbox__viewport-wrapper',
          ref: function ref(_ref2) {
            return _this3.imgWrapper = _ref2;
          },
          style: imageContainerStyles
        },
        viewport
      );
    };

    var leftArrowControl = _react2.default.createElement(
      _.Tooltip,
      { tooltip: tooltips.previous, direction: 'right-center' },
      _react2.default.createElement(
        'div',
        {
          className: 'cui-lightbox__page-control cui-lightbox__page-control-icon cui-lightbox__page-controls--left',
          role: 'button',
          tabIndex: '0',
          onKeyPress: function onKeyPress(e) {
            return _this3.triggerPageChange(index - 1, e);
          },
          onClick: function onClick(e) {
            return _this3.triggerPageChange(index - 1, e);
          },
          style: { transform: 'rotate(-180deg)' }
        },
        _ref3
      )
    );

    var rightArrowControl = _react2.default.createElement(
      _.Tooltip,
      { tooltip: tooltips.next, direction: 'left-center' },
      _react2.default.createElement(
        'div',
        {
          className: 'cui-lightbox__page-control cui-lightbox__page-control-icon cui-lightbox__page-controls--right',
          role: 'button',
          tabIndex: '0',
          onKeyPress: function onKeyPress(e) {
            return _this3.triggerPageChange(index + 1, e);
          },
          onClick: function onClick(e) {
            return _this3.triggerPageChange(index + 1, e);
          }
        },
        _ref4
      )
    );

    var viewportControls = function viewportControls() {
      var downloadButton = _react2.default.createElement(
        'div',
        {
          className: 'cui-lightbox__control cui-lightbox__control-download',
          tabIndex: '0',
          role: 'button',
          onClick: _this3.handleDownload,
          onKeyPress: _this3.handleDownload
        },
        _ref5
      );

      var controlStyle = currentPage.content ? {
        visibility: 'hidden'
      } : {};

      var pageControl = pages.length > 1 ? _react2.default.createElement(
        'div',
        { className: 'cui-lightbox__controls cui-lightbox__controls--center' },
        _react2.default.createElement(
          _.Tooltip,
          { tooltip: tooltips.previous },
          _react2.default.createElement(
            'div',
            { className: 'cui-lightbox__control',
              onClick: function onClick(e) {
                return _this3.triggerPageChange(index - 1, e);
              },
              role: 'button',
              tabIndex: '0',
              onKeyPress: function onKeyPress(e) {
                return _this3.triggerPageChange(index - 1, e);
              },
              style: { transform: 'rotate(-180deg)' }
            },
            _ref6
          )
        ),
        _react2.default.createElement(
          'span',
          { className: 'cui-lightbox__control-value' },
          index + 1 + ' / ' + pages.length
        ),
        _react2.default.createElement(
          _.Tooltip,
          { tooltip: tooltips.next },
          _react2.default.createElement(
            'div',
            { className: 'cui-lightbox__control',
              role: 'button',
              onClick: function onClick(e) {
                return _this3.triggerPageChange(index + 1, e);
              },
              tabIndex: '0',
              onKeyPress: function onKeyPress(e) {
                return _this3.triggerPageChange(index + 1, e);
              }
            },
            _ref7
          )
        )
      ) : _react2.default.createElement(
        'div',
        { className: 'cui-lightbox__controls' },
        _react2.default.createElement(
          'span',
          { className: 'cui-lightbox__control-value' },
          index + 1
        )
      );

      return _react2.default.createElement(
        'div',
        {
          className: 'cui-lightbox__viewer-controls',
          onClick: _this3.stopPropagation,
          onKeyPress: _this3.stopPropagation,
          role: 'button',
          tabIndex: '0'
        },
        _react2.default.createElement(
          'div',
          { className: 'cui-lightbox__controls', style: controlStyle },
          _react2.default.createElement(
            _.Tooltip,
            { tooltip: tooltips.zoomOut },
            _react2.default.createElement(
              'div',
              { className: 'cui-lightbox__control',
                onClick: function onClick() {
                  return _this3.setZoom(-0.25);
                },
                role: 'button',
                tabIndex: '0',
                onKeyPress: function onKeyPress() {
                  return _this3.setZoom(-0.25);
                }
              },
              _ref8
            )
          ),
          _react2.default.createElement(
            'span',
            { className: 'cui-lightbox__control-value' },
            Math.round(zoom * 100),
            '%'
          ),
          _react2.default.createElement(
            _.Tooltip,
            { tooltip: tooltips.zoomIn },
            _react2.default.createElement(
              'div',
              { className: 'cui-lightbox__control',
                role: 'button',
                onClick: function onClick() {
                  return _this3.setZoom(0.25);
                },
                tabIndex: '0',
                onKeyPress: function onKeyPress() {
                  return _this3.setZoom(0.25);
                }
              },
              _ref9
            )
          )
        ),
        pageControl,
        _react2.default.createElement(
          'div',
          { className: 'cui-lightbox__controls', style: controlStyle },
          _react2.default.createElement(
            'span',
            { className: 'cui-lightbox__control-value' },
            info.size
          ),
          _react2.default.createElement(
            _.Tooltip,
            { tooltip: downloading ? tooltips.downloading : tooltips.download },
            downloading ? _ref10 : downloadButton
          )
        )
      );
    };

    return _react2.default.createElement(
      _reactAriaModal2.default,
      {
        includeDefaultStyles: false,
        getApplicationNode: function getApplicationNode() {
          return document.querySelector('#' + applicationId);
        },
        onExit: this.handleClose,
        focusDialog: true,
        titleId: 'cui-lightbox',
        dialogClass: 'cui-lightbox',
        underlayClass: 'cui-lightbox__container'
      },
      _react2.default.createElement(
        'div',
        { className: 'cui-lightbox__header', ref: function ref(_ref12) {
            return _this3.lightBox = _ref12;
          } },
        _react2.default.createElement(
          'div',
          { className: 'cui-lightbox__header-item--left' },
          _react2.default.createElement(
            'div',
            { className: 'cui-lightbox__header-meta' },
            _react2.default.createElement(
              'div',
              { className: 'cui-lightbox__header-sharer' },
              info.sharedBy
            ),
            _react2.default.createElement(
              'div',
              { className: 'cui-lightbox__header-timestamp' },
              info.sharedOn
            )
          )
        ),
        _react2.default.createElement(
          'div',
          { className: 'cui-lightbox__header-item--center' },
          _react2.default.createElement(
            'div',
            { className: 'cui-lightbox__header-name' },
            name
          )
        ),
        _react2.default.createElement(
          'div',
          { className: 'cui-lightbox__header-item--right' },
          _react2.default.createElement(
            _.Tooltip,
            { tooltip: tooltips.exit, direction: 'bottom-right' },
            _react2.default.createElement(
              'div',
              { className: 'cui-lightbox__control',
                onClick: this.handleClose,
                role: 'button',
                tabIndex: '0',
                onKeyPress: this.handleClose },
              _ref11
            )
          )
        )
      ),
      _react2.default.createElement(
        'div',
        { className: 'cui-lightbox__body' },
        showColumn && getThumbnails(),
        _react2.default.createElement(
          'div',
          {
            className: 'cui-lightbox__content',
            onClick: this.handleClose,
            onKeyPress: this.handleClose,
            role: 'button',
            tabIndex: '0'
          },
          _react2.default.createElement(
            'div',
            {
              className: 'cui-lightbox__viewport' + ('' + (!!currentPage.decrypting && ' cui-lightbox__viewport--decrypting' || '')),
              ref: function ref(_ref14) {
                return _this3.viewport = _ref14;
              }
            },
            pages[index].decrypting && _ref13,
            getViewport()
          ),
          showColumn && leftArrowControl,
          showColumn && rightArrowControl,
          viewportControls()
        )
      )
    );
  };

  return Lightbox;
}(_react2.default.Component);

Lightbox.displayName = 'Lightbox';
exports.default = Lightbox;


Lightbox.defaultProps = {
  decrypting: false,
  downloading: false,
  index: 0,
  info: {},
  name: '',
  onChange: null,
  onClose: null,
  onDownload: null,
  tooltips: {
    download: 'Download',
    downloading: 'Downloading...',
    exit: 'Exit',
    previous: 'Previous',
    next: 'Next',
    zoomIn: 'Zoom in',
    zoomOut: 'Zoom out'
  }
};

/**
* @name Lightbox with one page
*
* @category containers
* @component lightbox
* @section default
*
* @js

import reactIcon from '@collab-ui/core/docs/assets/react.png';

 export default class Default extends React.Component {

  state = {
    index: 0,
    show: false,
    downloading: false,
  }

  render() {
    return (
      <div>
        <button onClick={() => this.setState({ show: true })}>Show</button>
        {
          this.state.show &&
          <Lightbox
            onClose={() => this.setState({ show: false})}
            onChange={(idx) => this.setState({ index: idx })}
            name="Screen Shot 2018-04-11 at 7.32.51 PM.png"
            applicationId="app"
            onDownload={() => {
                this.setState({downloading: true});
                setTimeout(() => this.setState({downloading: false}), 2000);
              }
            }
            downloading={this.state.downloading}
            info={{sharedBy:"Shared by test", sharedOn: "At 4/17/2018, 10:02 AM", size: "34.4 KB"}}
            index={this.state.index}
            height={250}
            width={250}
            pages={[{
              decrypting: false,
              image: reactIcon,
              thumb: reactIcon
            }]}
          />
        }
      </div>
    );
  }
}
**/

/**
* @name Lightbox with multiple page
*
* @category containers
* @component lightbox
* @section multiple
*
* @js

import reactIcon from '@collab-ui/core/docs/assets/react.png';
import angularIcon from '@collab-ui/core/docs/assets/angular.png';

 export default class Default extends React.Component {

  state = {
    index: 0,
    show: false,
    downloading: false,
  }

  render() {
    return (
      <div>
        <button onClick={() => this.setState({ show: true })}>Show</button>
        {
          this.state.show &&
          <Lightbox
            onClose={() => this.setState({ show: false})}
            onChange={(idx) => this.setState({ index: idx })}
            name="Screen Shot 2018-04-11 at 7.32.51 PM.png"
            applicationId="app"
            onDownload={() => {
                this.setState({downloading: true});
                setTimeout(() => this.setState({downloading: false}), 2000);
              }
            }
            downloading={this.state.downloading}
            info={{sharedBy:"Shared by test", sharedOn: "At 4/17/2018, 10:02 AM", size: "34.4 KB"}}
            index={this.state.index}
            height={250}
            width={250}
            pages={[{
              decrypting: false,
              image: reactIcon,
              thumb: reactIcon
            }, {
              decrypting: false,
              image: angularIcon,
              thumb: angularIcon
            }]}
          />
        }
      </div>
    );
  }
}
**/

module.exports = exports['default'];