'use strict';

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

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 _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _dropdown = require('kitten/components/dropdowns/dropdown');

var _buttonImageWithTextAndBadge = require('kitten/components/buttons/button-image-with-text-and-badge');

var _navList = require('kitten/components/lists/nav-list');

var _elementHelper = require('kitten/helpers/dom/element-helper');

var _elementHelper2 = _interopRequireDefault(_elementHelper);

var _emitter = require('kitten/helpers/utils/emitter');

var _emitter2 = _interopRequireDefault(_emitter);

var _assign = require('core-js/library/fn/object/assign');

var _assign2 = _interopRequireDefault(_assign);

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

var UserMenu = exports.UserMenu = function (_Component) {
  _inherits(UserMenu, _Component);

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

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

    _this.state = {
      isExpanded: false,
      contentPosition: { top: 0, left: 0 },
      arrowPosition: { top: 0, left: 0 }
    };

    _this.handleButtonClick = _this.handleButtonClick.bind(_this);
    _this.handlePositionUpdate = _this.handlePositionUpdate.bind(_this);
    _this.handleOtherDropdownsOpening = _this.handleOtherDropdownsOpening.bind(_this);
    return _this;
  }

  _createClass(UserMenu, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var _this2 = this;

      this.handlePositionUpdate();

      _emitter2.default.on('dropdown:opening:trigger', this.handleOtherDropdownsOpening);

      if (this.props.closeEvents) {
        this.props.closeEvents.forEach(function (ev) {
          window.addEventListener(ev, _this2.handleOtherDropdownsOpening);
        });
      }
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      var _this3 = this;

      if (this.props.closeEvents) {
        this.props.closeEvents.forEach(function (ev) {
          window.removeEventListener(ev, _this3.handleOtherDropdownsOpening);
        });
      }
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      if (this.shouldUpdatePosition(prevProps)) {
        this.handlePositionUpdate();
      }
    }

    // Component methods.

  }, {
    key: 'shouldUpdatePosition',
    value: function shouldUpdatePosition(prevProps) {
      return prevProps != this.props;
    }
  }, {
    key: 'getButtonId',
    value: function getButtonId() {
      return 'k-UserMenu';
    }
  }, {
    key: 'canComputeSize',
    value: function canComputeSize() {
      return _elementHelper2.default.canUseDom() && typeof this.refs.dropdown != 'undefined';
    }
  }, {
    key: 'getDropdownContainer',
    value: function getDropdownContainer() {
      return this.refs.dropdown.refs.dropdown.parentNode;
    }
  }, {
    key: 'getDropdownContainerWidth',
    value: function getDropdownContainerWidth() {
      return _elementHelper2.default.getComputedWidth(this.getDropdownContainer());
    }
  }, {
    key: 'getButtonImageElement',
    value: function getButtonImageElement() {
      return this.refs.dropdownButton.refs.buttonImage;
    }
  }, {
    key: 'getButtonImageElementHalfWidth',
    value: function getButtonImageElementHalfWidth() {
      return _elementHelper2.default.getComputedWidth(this.getButtonImageElement()) / 2;
    }
  }, {
    key: 'getDropdownContentElement',
    value: function getDropdownContentElement() {
      return this.refs.dropdown.refs.dropdownContent;
    }
  }, {
    key: 'getDropdownContentElementHalfWidth',
    value: function getDropdownContentElementHalfWidth() {
      return _elementHelper2.default.getComputedWidth(this.getDropdownContentElement()) / 2;
    }
  }, {
    key: 'getContentHorizontalPosition',
    value: function getContentHorizontalPosition() {
      // Compute dropdown position depending on the button image position.
      var space = this.getDropdownContainerWidth() + this.props.spaceAroundGrid - this.getButtonImageElementHalfWidth() - this.getDropdownContentElementHalfWidth();

      // If the interval is negative, just stick the dropdown to the reference
      // element border.
      space = space < 0 ? 0 : space;

      return { right: space + 'px' };
    }
  }, {
    key: 'getArrowHorizontalPosition',
    value: function getArrowHorizontalPosition() {
      var contentHorizontalPositionValue = parseInt(this.getContentHorizontalPosition().right, 10);

      // Compute arrow position depending on the button image position.
      var space = this.getDropdownContainerWidth() + this.props.spaceAroundGrid - this.getButtonImageElementHalfWidth() - contentHorizontalPositionValue;

      return { right: space + 'px' };
    }
  }, {
    key: 'getDropdownContent',
    value: function getDropdownContent() {
      return _react2.default.createElement(_navList.NavList, {
        className: (0, _classnames2.default)('k-UserMenu', 'k-UserMenu--withoutBorderTop'),
        role: 'menubar',
        list: this.props.dropdownList
      });
    }
  }, {
    key: 'getDropdownButton',
    value: function getDropdownButton() {
      return _react2.default.createElement(_buttonImageWithTextAndBadge.ButtonImageWithTextAndBadge, {
        ref: 'dropdownButton',
        className: this.props.buttonClassName,
        id: this.getButtonId(),
        isExpanded: this.state.isExpanded,
        onClick: this.handleButtonClick,
        srcImg: this.props.buttonImgSrc,
        widthImg: this.props.buttonImgWidth,
        heightImg: this.props.buttonImgHeight,
        altImg: this.props.buttonImgAlt,
        text: this.props.buttonText,
        title: this.props.buttonTitle,
        notifications: this.props.buttonNotifications,
        textClassName: 'k-Header__userMenuText--withEllipsis'
      });
    }
  }, {
    key: 'getDropdownArrow',
    value: function getDropdownArrow() {
      return _react2.default.createElement('span', { className: 'k-UserMenu__arrow' });
    }
  }, {
    key: 'updateDropdownContentPosition',
    value: function updateDropdownContentPosition() {
      this.setState({
        contentHorizontalPosition: this.getContentHorizontalPosition()
      });
    }
  }, {
    key: 'updateDropdownArrowPosition',
    value: function updateDropdownArrowPosition() {
      this.setState({
        arrowHorizontalPosition: this.getArrowHorizontalPosition()
      });
    }

    // Component listener callbacks.

  }, {
    key: 'handlePositionUpdate',
    value: function handlePositionUpdate() {
      if (this.canComputeSize()) {
        this.updateDropdownContentPosition();
        this.updateDropdownArrowPosition();
      }
    }
  }, {
    key: 'handleButtonClick',
    value: function handleButtonClick(event) {
      event.stopPropagation();
      event.preventDefault();

      this.setState({ isExpanded: !this.state.isExpanded });
    }
  }, {
    key: 'handleOtherDropdownsOpening',
    value: function handleOtherDropdownsOpening(openedDropdown) {
      if (openedDropdown != this.refs.dropdown) {
        this.setState({ isExpanded: false });
      }
    }

    // Rendering.

  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          dropdownList = _props.dropdownList,
          otherProps = _objectWithoutProperties(_props, ['dropdownList']);

      return _react2.default.createElement(_dropdown.Dropdown, _extends({
        ref: 'dropdown',
        button: this.getDropdownButton(),
        dropdownContent: this.getDropdownContent(),
        dropdownListArrow: this.getDropdownArrow(),
        contentHorizontalPosition: this.state.contentHorizontalPosition,
        arrowHorizontalPosition: this.state.arrowHorizontalPosition,
        isExpanded: this.state.isExpanded,
        buttonId: this.getButtonId(),
        onPositionUpdate: this.handlePositionUpdate
      }, otherProps));
    }
  }]);

  return UserMenu;
}(_react.Component);

UserMenu.propTypes = {
  buttonClassName: _propTypes2.default.string,
  buttonImgSrc: _propTypes2.default.string,
  buttonImgWidth: _propTypes2.default.number,
  buttonImgHeight: _propTypes2.default.number,
  buttonImgAlt: _propTypes2.default.string,
  buttonText: _propTypes2.default.string,
  buttonTitle: _propTypes2.default.string,
  dropdownList: _propTypes2.default.array,
  positionedWith: _propTypes2.default.func,
  positionedWithBorder: _propTypes2.default.bool,
  positionedOn: _propTypes2.default.string,
  notifications: _propTypes2.default.number,
  refreshEvents: _propTypes2.default.array,
  closeEvents: _propTypes2.default.array,
  onPositionUpdate: _propTypes2.default.func
};

UserMenu.defaultProps = {
  // Add custom value to compute horizontal position
  spaceAroundGrid: 0,

  // Notifications count on badge.
  buttonNotifications: 0

  // DEPRECATED: do not use default export.
};exports.default = UserMenu;