'use strict';

exports.__esModule = true;

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

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 _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _List = require('../List');

var _List2 = _interopRequireDefault(_List);

var _Icon = require('../Icon');

var _Icon2 = _interopRequireDefault(_Icon);

var _Button = require('../Button');

var _Button2 = _interopRequireDefault(_Button);

var _EventOverlay = require('../EventOverlay');

var _EventOverlay2 = _interopRequireDefault(_EventOverlay);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

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

/**
 * @category controls
 * @component time-picker
 * @variations collab-ui-react
 */

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

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

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

    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 = {
      isOpen: false,
      selected: [],
      selectedIndex: [],
      anchorNode: null,
      anchorWidth: null,
      id: _this.props.id || _lodash2.default.uniqueId('cui-select-'),
      visibleProp: 'bottom-center'
    }, _this.hidePopover = function () {
      _this.setState({
        isOpen: false
      });
    }, _this.handleSelect = function (e, value, index) {
      e.preventDefault();
      var _this$state = _this.state,
          selected = _this$state.selected,
          selectedIndex = _this$state.selectedIndex;
      var isMulti = _this.props.isMulti;

      var isActive = selected.includes(value);
      !isMulti && _this.setState({ isOpen: false });
      if (isActive && !isMulti) return;

      if (isActive && isMulti) {
        return _this.setState({
          selected: selected.filter(function (v) {
            return v !== value;
          }),
          selectedIndex: selectedIndex.filter(function (i) {
            return i !== index;
          })
        });
      } else if (!isActive && !isMulti) {
        return _this.setState({
          selected: [value],
          selectedIndex: [index]
        });
      } else {
        return _this.setState({
          selected: [].concat(selected, [value]),
          selectedIndex: [].concat(selectedIndex, [index])
        });
      }
    }, _this.choosePosition = function () {
      _this.state.isOpen && _this.isVisible(_reactDom2.default.findDOMNode(_this.list), _this.state.anchorNode);
    }, _this.handleToggle = function () {
      _this.setState({
        isOpen: !_this.state.isOpen,
        anchorNode: _reactDom2.default.findDOMNode(_this.clickTextField).parentNode
      }, function () {
        return _this.choosePosition();
      });
    }, _this.isVisible = function (element, elementAnchor) {
      var tempParentArr = [];
      var anchor = elementAnchor && elementAnchor.getBoundingClientRect();
      var elementBoundingRect = element.getBoundingClientRect();
      var elementParent = element.parentElement;
      var windowBottom = window.pageXOffset + window.innerHeight;
      var elementHeight = elementBoundingRect.height;
      var anchorWidth = anchor.width;
      var anchorBottom = anchor.bottom;
      var totalHeight = anchorBottom + elementHeight;

      var findParents = function findParents(elem) {
        return !elem.parentElement ? tempParentArr : findParents(elem.parentElement, tempParentArr.push(elem));
      };

      var elementParents = findParents(elementParent);

      var findOverflow = function findOverflow(node) {
        var searchProps = ['overflow', 'overflow-y'];

        return searchProps.reduce(function (agg, prop) {
          var overflowElement = _reactDom2.default.findDOMNode(node).style[prop];

          return !overflowElement || agg.includes(overflowElement) ? agg : agg += overflowElement;
        }, '');
      };

      var findScrollParent = function findScrollParent() {
        var overflowElement = null;
        var idx = 0;

        while (!overflowElement && elementParents[idx]) {
          if (/(auto|scroll)/.test(findOverflow(elementParents[idx]))) {
            return overflowElement = elementParents[idx];
          }
          idx++;
        }

        return overflowElement ? overflowElement : window;
      };

      var scrollParent = findScrollParent(element);
      var parentBottom = !!scrollParent.getBoundingClientRect && scrollParent.getBoundingClientRect().bottom || windowBottom;

      return totalHeight < parentBottom && totalHeight < windowBottom ? _this.setState({ visibleProp: 'bottom-center', anchorWidth: anchorWidth }) : _this.setState({ visibleProp: 'top-center', anchorWidth: anchorWidth });
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  Select.prototype.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
    prevState.selected !== this.state.selected && this.props.onSelect && this.props.onSelect(this.state.selected);
  };

  Select.prototype.render = function render() {
    var _this2 = this;

    var _props = this.props,
        children = _props.children,
        className = _props.className,
        isMulti = _props.isMulti,
        defaultValue = _props.defaultValue,
        props = (0, _objectWithoutProperties3.default)(_props, ['children', 'className', 'isMulti', 'defaultValue']);
    var _state = this.state,
        selected = _state.selected,
        selectedIndex = _state.selectedIndex,
        isOpen = _state.isOpen,
        visibleProp = _state.visibleProp,
        anchorNode = _state.anchorNode,
        anchorWidth = _state.anchorWidth,
        id = _state.id;


    var currentValue = function currentValue() {
      if (!isMulti) return selected[0];

      if (selected.length === 1) {
        return selected.length + ' Item Selected';
      } else if (selected.length) {
        return selected.length + ' Items Selected';
      }
    };

    var label = _react2.default.createElement(
      'div',
      { className: 'cui-select__label', id: id + '__label' },
      currentValue() || defaultValue,
      _react2.default.createElement(_Icon2.default, { name: 'arrow-down_16', isAria: false })
    );

    var text = _react2.default.createElement(_Button2.default, (0, _extends3.default)({
      name: id,
      id: id,
      children: label,
      onClick: this.handleToggle,
      ref: function ref(_ref) {
        return _this2.clickTextField = _ref;
      },
      className: 'cui-button--input' + ('' + (className && ' ' + className || '')),
      'aria-haspopup': 'listbox',
      ariaLabelledBy: id + '__label',
      active: isOpen
    }, props));

    var dropdownElement = _react2.default.createElement(
      _EventOverlay2.default,
      {
        allowClickAway: true,
        anchorNode: anchorNode,
        close: this.hidePopover,
        isOpen: isOpen,
        direction: visibleProp
      },
      _react2.default.createElement(
        _List2.default,
        {
          onSelect: this.handleSelect,
          style: { width: anchorWidth },
          ref: function ref(_ref2) {
            return _this2.list = _ref2;
          },
          role: 'listbox',
          itemRole: 'option',
          active: selectedIndex,
          isMulti: isMulti,
          'aria-labelledby': id + '__label',
          'aria-multiselectable': isMulti
        },
        children
      )
    );

    return _react2.default.createElement(
      'div',
      { className: 'cui-input-group cui-select' },
      text,
      dropdownElement
    );
  };

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

Select.displayName = 'Select';
exports.default = Select;


Select.defaultProps = {
  className: '',
  children: null,
  defaultValue: '',
  id: null,
  isMulti: false,
  onSelect: null
};

/**
* @name Default Select
* @description Selects can be used for single or multi-select
*
* @category controls
* @component select
* @section default
*
* @js
import { SelectOption } from '@collab-ui/react';

export default class DefaultSelect extends React.PureComponent {
  render() {
    return (
      <div className="medium-6 columns">
        <Select defaultValue='Select Item Here' >
          <SelectOption value='test1' label='test1' />
          <SelectOption value='test2' label='test2' />
          <SelectOption value='test3' label='test3' />
          <SelectOption value='test4' label='test4' />
        </Select>
      </div>
    );
  }
}

**/

/**
* @name Multi-Select
* @description Selects can be used for multi-select
*
* @category controls
* @component select
* @section multi-select
*
* @js
import { SelectOption } from '@collab-ui/react';

export default class DefaultSelect extends React.PureComponent {
  render() {
    return (
      <div className="medium-6 columns">
        <Select isMulti defaultValue='Select Item Here' >
          <SelectOption value='test1' label='test1' />
          <SelectOption value='test2' label='test2' />
          <SelectOption value='test3' label='test3' />
          <SelectOption value='test4' label='test4' />
        </Select>
      </div>
    );
  }
}

**/

/**
* @name Disabled
* @description Selects can be disabled
*
* @category controls
* @component select
* @section disabled
*
* @js
import { SelectOption } from '@collab-ui/react';

export default class DisabledSelect extends React.PureComponent {
  render() {
    return (
      <div className="medium-6 columns">
        <Select defaultValue='Select Item Here' disabled>
          <SelectOption value='test1' label='test1' />
          <SelectOption value='test2' label='test2' />
          <SelectOption value='test3' label='test3' />
          <SelectOption value='test4' label='test4' />
        </Select>
      </div>
    );
  }
}

**/

module.exports = exports['default'];