"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _react = _interopRequireDefault(require("react"));

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

var _reduxForm = require("redux-form");

var _utils = require("@vincent_za/utils");

var _form = require("../../form");

var _constants = require("../constants");

var _shared = require("../shared");

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

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var Base =
/*#__PURE__*/
function (_React$Component) {
  _inherits(Base, _React$Component);

  function Base(props) {
    var _this;

    _classCallCheck(this, Base);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(Base).call(this, props));

    _defineProperty(_assertThisInitialized(_this), "onSearchDebounced", function (event) {
      _this.props.onSearch(event.target.value);
    });

    _defineProperty(_assertThisInitialized(_this), "onBlur", function () {
      _this.timeoutID = setTimeout(function () {
        if (_this.state.isOpen) {
          _this.setState({
            isOpen: false,
            isFocused: false
          });
        }
      }, 0);
    });

    _defineProperty(_assertThisInitialized(_this), "onFocus", function () {
      clearTimeout(_this.timeoutID);

      if (!_this.state.isOpen) {
        _this.setState({
          isFocused: true
        });
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onItemClick", function (item) {
      var _this$props = _this.props,
          isCloseOnSelect = _this$props.isCloseOnSelect,
          onItemClick = _this$props.onItemClick;

      _this.onSearchDebounced.cancel();

      onItemClick(item);
      isCloseOnSelect && _this.toggleDropdown();
    });

    _defineProperty(_assertThisInitialized(_this), "toggleDropdown", function () {
      var _assertThisInitialize = _assertThisInitialized(_this),
          isOpen = _assertThisInitialize.state.isOpen,
          _assertThisInitialize2 = _assertThisInitialize.props,
          isDisabled = _assertThisInitialize2.isDisabled,
          isInfo = _assertThisInitialize2.isInfo,
          onToggleDropdownCb = _assertThisInitialize2.onToggleDropdownCb,
          asyncStatus = _assertThisInitialize2.asyncStatus,
          asyncStatusList = _assertThisInitialize2.asyncStatusList;

      var _determineAsyncStatus = (0, _utils.determineAsyncStatus)({
        asyncStatus: asyncStatus,
        asyncStatusList: asyncStatusList
      }),
          isError = _determineAsyncStatus.isError;

      clearTimeout(_this.timeoutID);
      if (isDisabled || isInfo || isError) return _this.setState({
        isOpen: false,
        isFocused: false
      });

      _this.updateRectResize();

      if (isOpen) {
        _this.setState({
          isOpen: false,
          isFocused: false
        });
      } else {
        _this.setState({
          isOpen: true,
          isFocused: true
        });
      }

      onToggleDropdownCb && onToggleDropdownCb();
    });

    _defineProperty(_assertThisInitialized(_this), "addDropdownRef", function (el) {
      _this.dropdownRef = el;
    });

    _defineProperty(_assertThisInitialized(_this), "addMenuRef", function (el) {
      _this.menuRef = el;
    });

    _defineProperty(_assertThisInitialized(_this), "updateRectScroll", function () {
      !_this.props.isInWidget && _this.setState({
        clientRect: _this.dropdownRef.getBoundingClientRect()
      });
    });

    _defineProperty(_assertThisInitialized(_this), "updateRectResize", function () {
      _this.setState({
        clientRect: _this.dropdownRef.getBoundingClientRect()
      });
    });

    _this.state = {
      isOpen: false,
      isFocused: false,
      isMenuCutOff: false,
      clientRect: _utils.DEFAULT_RECT.getBoundingClientRect()
    };
    _this.timeoutID = undefined;
    _this.onSearchDebounced = (0, _utils.debounce)(200)(_this.onSearchDebounced);
    _this.updateRectScroll = (0, _utils.throttle)(200)(_this.updateRectScroll);
    _this.updateRectResize = (0, _utils.throttle)(200)(_this.updateRectResize);
    return _this;
  }

  _createClass(Base, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var domScrollSelector = this.props.domScrollSelector;
      var scrollSelector = domScrollSelector ? document.querySelector(domScrollSelector) : window;
      scrollSelector.addEventListener('scroll', this.updateRectScroll);
      window.addEventListener('resize', this.updateRectResize);
      this.setState({
        clientRect: this.dropdownRef.getBoundingClientRect()
      });
    }
  }, {
    key: "shouldComponentUpdate",
    value: function shouldComponentUpdate(nextProps, nextState) {
      if (nextState.isOpen !== this.state.isOpen) return true;
      if (nextState.isFocused !== this.state.isFocused) return true;
      if (nextState.isMenuCutOff !== this.state.isMenuCutOff) return true;
      if (nextState.clientRect !== this.state.clientRect) return true;
      if (nextProps.isHidden !== this.props.isHidden) return true;
      if (nextProps.isClick !== this.props.isClick) return true;
      if (nextProps.isDisabled !== this.props.isDisabled) return true;
      if (nextProps.isInfo !== this.props.isInfo) return true;
      if (nextProps.activeItem !== this.props.activeItem) return true;
      if (nextProps.renderHeader !== this.props.renderHeader) return true;
      if (nextProps.renderMenu !== this.props.renderMenu) return true;
      if (nextProps.asyncStatus !== this.props.asyncStatus) return true;
      if (nextProps.asyncStatusList !== this.props.asyncStatusList) return true;
      return false;
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      var _this$state = this.state,
          isOpen = _this$state.isOpen,
          isMenuCutOff = _this$state.isMenuCutOff;

      if (isOpen) {
        var _this$menuRef$getBoun = this.menuRef.getBoundingClientRect(),
            menuY = _this$menuRef$getBoun.y,
            menuHeight = _this$menuRef$getBoun.height; // const { height: appHeight } = document.querySelector('#app').getBoundingClientRect();
        // const isMenuCutOffUpdated = (menuY + menuHeight) > appHeight;


        var isMenuCutOffUpdated = false;
        if (!isMenuCutOff && isMenuCutOffUpdated === true) this.setState({
          isMenuCutOff: true
        });
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var domScrollSelector = this.props.domScrollSelector;
      var scrollSelector = domScrollSelector ? document.querySelector(domScrollSelector) : window;
      clearTimeout(this.timeoutID);
      scrollSelector.removeEventListener('scroll', this.updateRectScroll);
      window.removeEventListener('resize', this.updateRectResize);
    }
  }, {
    key: "render",
    value: function render() {
      var _this$state2 = this.state,
          isMenuCutOff = _this$state2.isMenuCutOff,
          clientRect = _this$state2.clientRect;
      var _this$props2 = this.props,
          isFormVariant = _this$props2.isFormVariant,
          isHeaderStretchWidth = _this$props2.isHeaderStretchWidth,
          renderHeader = _this$props2.renderHeader,
          renderMenu = _this$props2.renderMenu,
          isHidden = _this$props2.isHidden,
          isMenuHeaderWidth = _this$props2.isMenuHeaderWidth,
          isMenuHeaderWidthMin = _this$props2.isMenuHeaderWidthMin,
          isClick = _this$props2.isClick,
          isDisabled = _this$props2.isDisabled,
          isInfo = _this$props2.isInfo,
          isTop = _this$props2.isTop,
          isRight = _this$props2.isRight,
          isBottom = _this$props2.isBottom,
          isNoMaxHeight = _this$props2.isNoMaxHeight,
          isInWidget = _this$props2.isInWidget,
          activeItem = _this$props2.activeItem,
          fieldName = _this$props2.fieldName,
          asyncStatus = _this$props2.asyncStatus,
          asyncStatusList = _this$props2.asyncStatusList,
          className = _this$props2.className;

      var _determineAsyncStatus2 = (0, _utils.determineAsyncStatus)({
        asyncStatus: asyncStatus,
        asyncStatusList: asyncStatusList
      }),
          isError = _determineAsyncStatus2.isError;

      var isOpen = this.state.isFocused && this.state.isOpen;
      var hasActiveItem = activeItem !== '' && activeItem !== undefined;
      return _react.default.createElement(_shared.DropdownWrap, {
        isHeaderStretchWidth: isHeaderStretchWidth,
        isClick: isClick,
        isOpen: isOpen,
        isDisabled: isDisabled,
        isInfo: isInfo,
        isError: isError,
        isHidden: isHidden,
        className: className,
        tabIndex: 0,
        onBlur: this.onBlur,
        onFocus: this.onFocus,
        onMouseEnter: !isClick ? this.toggleDropdown : function () {},
        onMouseLeave: !isClick ? this.toggleDropdown : function () {},
        ref: this.addDropdownRef
      }, renderHeader({
        isOpen: isOpen,
        hasActiveItem: hasActiveItem,
        onClick: isClick ? this.toggleDropdown : function () {}
      }), fieldName && _react.default.createElement(_reduxForm.Field, {
        isHidden: true,
        name: fieldName,
        id: fieldName,
        component: _form.TextField
      }), isOpen && _react.default.createElement(_shared.MenuScroll, {
        isFormVariant: isFormVariant,
        isClick: isClick,
        isOpen: isOpen,
        isError: isError,
        isDisabled: isDisabled,
        isInfo: isInfo,
        isMenuHeaderWidth: isMenuHeaderWidth,
        isMenuHeaderWidthMin: isMenuHeaderWidthMin,
        isLightScrollVariant: true,
        isNoMaxHeight: isNoMaxHeight,
        isTop: isTop,
        isRight: isRight,
        isBottom: isBottom,
        isMenuCutOff: isMenuCutOff,
        isInWidget: isInWidget,
        clientRect: clientRect,
        className: _constants.CL_DROPDOWN_MENU,
        passedRef: this.addMenuRef
      }, renderMenu({
        isMenuCutOff: isMenuCutOff,
        clientRect: clientRect,
        onClick: this.onItemClick,
        onSearchDebounced: this.onSearchDebounced
      })));
    }
  }]);

  return Base;
}(_react.default.Component);

Base.propTypes = {
  isCloseOnSelect: _propTypes.bool,
  isFormVariant: _propTypes.bool,
  isHeaderStretchWidth: _propTypes.bool,
  isHidden: _propTypes.bool,
  isMenuHeaderWidth: _propTypes.bool,
  isMenuHeaderWidthMin: _propTypes.bool,
  isClick: _propTypes.bool,
  isDisabled: _propTypes.bool,
  isInfo: _propTypes.bool,
  isTop: _propTypes.bool,
  isRight: _propTypes.bool,
  isBottom: _propTypes.bool,
  isNoMaxHeight: _propTypes.bool,
  isInWidget: _propTypes.bool.isRequired,
  activeItem: (0, _propTypes.oneOfType)([_propTypes.string, _propTypes.number]),
  domScrollSelector: _propTypes.string,
  fieldName: _propTypes.string,
  renderHeader: _propTypes.func.isRequired,
  renderMenu: _propTypes.func.isRequired,
  onToggleDropdownCb: _propTypes.func,
  onItemClick: _propTypes.func,
  onSearch: _propTypes.func,
  asyncStatus: (0, _propTypes.shape)(_utils.PROP_ASYNC_STATUS),
  asyncStatusList: (0, _propTypes.arrayOf)((0, _propTypes.shape)(_utils.PROP_ASYNC_STATUS)),
  className: _propTypes.string
};
Base.defaultProps = {
  isCloseOnSelect: true,
  isFormVariant: false,
  isHeaderStretchWidth: false,
  isHidden: false,
  isMenuHeaderWidth: false,
  isMenuHeaderWidthMin: false,
  isClick: false,
  isDisabled: false,
  isInfo: false,
  isTop: false,
  isRight: false,
  isBottom: false,
  isNoMaxHeight: false,
  activeItem: undefined,
  domScrollSelector: undefined,
  fieldName: undefined,
  onToggleDropdownCb: function onToggleDropdownCb() {},
  onItemClick: function onItemClick() {},
  onSearch: function onSearch() {},
  asyncStatus: _utils.SHAPE_ASYNC_STATUS_INITIAL,
  asyncStatusList: [],
  className: undefined
};
var _default = Base;
exports.default = _default;