"use strict";

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

var React = _interopRequireWildcard(require("react"));

var _withStyles = _interopRequireDefault(require("../../hoc/withStyles"));

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

var _get = _interopRequireDefault(require("lodash/get"));

var _isEqual = _interopRequireDefault(require("lodash/isEqual"));

var _classnames = _interopRequireDefault(require("classnames"));

var _Collapse = _interopRequireDefault(require("@material-ui/core/Collapse"));

var _idx = _interopRequireDefault(require("idx"));

var _findIndex = _interopRequireDefault(require("lodash/findIndex"));

var _ErrorBoundary = _interopRequireDefault(require("../../hoc/ErrorBoundary"));

var _FieldLabel = _interopRequireDefault(require("../FieldLabel"));

var _styles = _interopRequireDefault(require("./styles"));

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

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

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 _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 _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

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 Dropdown =
/*#__PURE__*/
function (_React$Component) {
  _inherits(Dropdown, _React$Component);

  function Dropdown(props) {
    var _this;

    _classCallCheck(this, Dropdown);

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

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "container", void 0);

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_selectValueFromProps", function () {
      var _this$props = _this.props,
          value = _this$props.value,
          items = _this$props.items,
          multiple = _this$props.multiple;

      _this.selectValue(items, value, multiple);
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_handleOutSideClick", function (e) {
      if (_this.container.contains(e.target)) {
        return;
      } // outside click


      _this.close();
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "open", function () {
      if (_this.props.disabled) {
        return;
      }

      _this.setState({
        isOpen: true
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "close", function () {
      _this.setState({
        isOpen: false
      });

      if (_this.props.onClose) {
        _this.props.onClose();
      }
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_toggle", function (e) {
      if (_this.state.isOpen) {
        _this.close();
      } else {
        _this.open();
      }

      if (_this.props.onClick) {
        _this.props.onClick(e);
      }
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "selectValue", function () {
      var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      var value = arguments.length > 1 ? arguments[1] : undefined;
      var multiple = arguments.length > 2 ? arguments[2] : undefined;

      if (typeof value === 'undefined' || value === null) {
        return;
      } // if it is singular selection nextSelectedIndex is number and nextSelectedItem object
      // if it is multiple selection nextSelectedIndex is array of index and nextSelectedItem array of items


      var nextSelectedIndex;
      var nextSelectedItem;

      if (_this.props.comparator) {
        var _this$props$comparato = _this.props.comparator(items.map(function (item) {
          return item.value;
        }), value),
            index = _this$props$comparato.index,
            item = _this$props$comparato.item;

        if (!multiple) {
          // if single selection, index is number and item is object
          nextSelectedIndex = index;
          nextSelectedItem = item;
        } else {
          // if multiple selection, index should be array of number and item should be array of object
          nextSelectedIndex = [].concat(index);
          nextSelectedItem = [].concat(item);
        }
      } else {
        // if comparator is not given then entire value object will be matched with given items
        if (!multiple) {
          nextSelectedIndex = (0, _findIndex.default)(items, {
            value: value
          });
          nextSelectedItem = (0, _idx.default)(items, function (_) {
            return _[nextSelectedIndex];
          });
        } else {
          nextSelectedIndex = [];
          nextSelectedItem = [];
          items.forEach(function (item, index) {
            if (value.indexOf(item.value) > -1) {
              nextSelectedIndex.push(index);
              nextSelectedItem.push(item);
            }
          });
        }
      }

      _this.setState({
        selectedIndex: nextSelectedIndex
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "reset", function () {
      _this.setState({
        selectedIndex: -1
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_handleChange", function (item, index) {
      var _this$props2 = _this.props,
          onChange = _this$props2.onChange,
          multiple = _this$props2.multiple;
      var isSelected = true;

      if (!multiple) {
        _this.setState({
          selectedIndex: index
        });
      } else {
        var selectedIndex = _this.state.selectedIndex;
        var pos = [].concat(selectedIndex || []).indexOf(index);
        var newSelectedIndex = [];

        if (selectedIndex instanceof Array) {
          newSelectedIndex = _toConsumableArray(selectedIndex);
        }

        if (pos > -1) {
          // index already exist so remove it from array
          newSelectedIndex.splice(pos, 1);
          isSelected = false;
        } else {
          // index doesn't exist so add it
          newSelectedIndex.push(index);
        }

        _this.setState({
          selectedIndex: newSelectedIndex
        });
      }

      if (onChange) {
        // isSelected is mainly used for multiple selection , whether item is checked or unchecked
        onChange(item, index, isSelected);
      }

      if (!multiple) {
        // if only single selection, then close dropdown on select
        _this.close();
      }
    });

    _this.state = {
      selectedIndex: props.selectedIndex,
      isOpen: false
    };
    return _this;
  }

  _createClass(Dropdown, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      if (typeof this.props.value !== 'undefined') {
        this._selectValueFromProps();
      }

      document.addEventListener('mousedown', this._handleOutSideClick, false);
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      document.removeEventListener('mousedown', this._handleOutSideClick, false);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState) {
      if (this.props.selectedIndex !== prevProps.selectedIndex) {
        this.setState({
          selectedIndex: this.props.selectedIndex
        });
      }

      if (!(0, _isEqual.default)(this.props.value, prevProps.value) || !(0, _isEqual.default)(this.props.items, prevProps.items)) {
        this._selectValueFromProps();
      }
    }
  }, {
    key: "_renderDropdown",
    value: function _renderDropdown() {
      var _this2 = this;

      var _this$props3 = this.props,
          classes = _this$props3.classes,
          label = _this$props3.label,
          placeholder = _this$props3.placeholder,
          items = _this$props3.items,
          disabled = _this$props3.disabled,
          error = _this$props3.error,
          multiple = _this$props3.multiple,
          className = _this$props3.className;
      var _this$state = this.state,
          isOpen = _this$state.isOpen,
          selectedIndex = _this$state.selectedIndex;
      var selectedLabel;

      if (!multiple) {
        selectedLabel = (0, _get.default)(items, "".concat(String(selectedIndex), ".label"));
      } else {
        if (selectedIndex instanceof Array) {
          var labels = [].concat(selectedIndex || []).map(function (val) {
            return (0, _get.default)(items, val + ".label");
          });
          selectedLabel = labels.join(', ');
        }
      }

      var selectedIcon;

      if (!multiple) {
        selectedIcon = React.createElement("div", {
          className: (0, _classnames.default)(classes.circleIcon)
        });
      } else {
        selectedIcon = React.createElement("i", {
          className: (0, _classnames.default)('fa fa-check', classes.tickIcon)
        });
      }

      return React.createElement("div", {
        className: (0, _classnames.default)(classes.root, {
          error: Boolean(error)
        }, className)
      }, label && React.createElement(_FieldLabel.default, {
        label: label,
        classes: {
          label: classes.label
        }
      }), React.createElement("div", {
        className: (0, _classnames.default)(classes.select, {
          open: isOpen,
          'is-value-selected': Boolean(selectedLabel),
          disabled: disabled
        }),
        onClick: this._toggle
      }, Boolean(placeholder) && !selectedLabel && React.createElement("div", {
        className: (0, _classnames.default)(classes.placeholder)
      }, placeholder), Boolean(selectedLabel) && React.createElement("div", {
        className: (0, _classnames.default)(classes.selectValue)
      }, selectedLabel), React.createElement("div", {
        className: (0, _classnames.default)(classes.arrowDown, {
          up: isOpen
        })
      })), React.createElement(_Collapse.default, {
        in: this.state.isOpen,
        timeout: "auto",
        unmountOnExit: true,
        classes: {
          container: (0, _classnames.default)(classes.selectMenu, {
            withoutLabel: !label
          })
        }
      }, React.createElement("div", {
        "data-test-id": "select-menu-wrapper"
      }, items.map(function (item, index) {
        var isItemSelected = false;

        if (!multiple) {
          isItemSelected = selectedIndex === index;
        } else {
          isItemSelected = [].concat(selectedIndex).indexOf(index) > -1;
        }

        return React.createElement("div", {
          "data-test-id": "item-".concat(index),
          key: index,
          className: (0, _classnames.default)(classes.menuItem),
          onClick: function onClick() {
            _this2._handleChange(item, index);
          }
        }, React.createElement("div", {
          className: (0, _classnames.default)(classes.menuItemText, {
            selected: isItemSelected
          })
        }, item.label), isItemSelected && selectedIcon);
      }))));
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      var _this$props4 = this.props,
          classes = _this$props4.classes,
          error = _this$props4.error,
          showErrorMessage = _this$props4.showErrorMessage,
          id = _this$props4.id;
      return React.createElement(_ErrorBoundary.default, null, React.createElement("div", {
        className: (0, _classnames.default)(classes.component),
        id: id,
        ref: function ref(_ref) {
          return _this3.container = _ref;
        }
      }, this._renderDropdown(), Boolean(error) && showErrorMessage && React.createElement("div", {
        className: classes.error
      }, error)));
    }
  }]);

  return Dropdown;
}(React.Component);

_defineProperty(Dropdown, "propTypes", {
  /** id **/
  id: _propTypes.default.string,

  /** label **/
  label: _propTypes.default.string,

  /** placeholder **/
  placeholder: _propTypes.default.string,

  /** called when item selection change **/
  onChange: _propTypes.default.func,

  /** called when dropdown selection change **/
  onClick: _propTypes.default.func,

  /** called when dropdown menu close **/
  onClose: _propTypes.default.func,

  /** disable dropdown **/
  disabled: _propTypes.default.bool,

  /** selcted index  **/
  selectedIndex: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.array]),

  /** items to display in dropdown  **/
  items: _propTypes.default.arrayOf(_propTypes.default.shape({
    label: _propTypes.default.string.isRequired,
    value: _propTypes.default.any.isRequired
  })).isRequired,

  /** error message **/
  error: _propTypes.default.string,

  /** should show error message (default : true) **/
  showErrorMessage: _propTypes.default.bool,

  /** value of selected item **/
  value: _propTypes.default.any,

  /** this is used to find selected value from given item  */
  comparator: _propTypes.default.func,

  /** multiple: to allow multiple selection, default: false */
  multiple: _propTypes.default.bool,

  /** classes  **/
  classes: _propTypes.default.object,

  /** custom css  **/
  className: _propTypes.default.string
});

_defineProperty(Dropdown, "defaultProps", {
  placeholder: 'Select',
  showErrorMessage: true,
  id: '',
  onChange: function onChange() {},
  onClick: function onClick() {},
  onClose: function onClose() {}
});

var _default = (0, _withStyles.default)(_styles.default)(Dropdown);

exports.default = _default;