import "core-js/modules/es6.object.assign";
import "core-js/modules/es6.regexp.match";
import "core-js/modules/es7.array.includes";
import "core-js/modules/es6.string.includes";

function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }

import React from 'react';
import PropTypes from 'prop-types';

var ButtonGroup =
/*#__PURE__*/
function (_React$Component) {
  _inheritsLoose(ButtonGroup, _React$Component);

  function ButtonGroup() {
    var _this;

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

    _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
    _this.state = {
      activeIndex: _this.props.activeIndex,
      focusIndex: 0
    };

    _this.getChildContext = function () {
      return {
        handleClick: function handleClick(event, index) {
          return _this.handleClick(event, index);
        },
        handleKeyDown: function handleKeyDown(event, index) {
          return _this.handleKeyDown(event, index);
        },
        focusIndex: _this.state.focusIndex,
        focusOnLoad: _this.props.focusOnLoad
      };
    };

    _this.verifyChildren = function () {
      var children = _this.props.children;
      var status = React.Children.toArray(children).reduce(function (status, child) {
        return status && child.type.displayName === 'Button';
      }, true);
      return status;
    };

    _this.determineInitialActive = function () {
      /* eslint-disable no-console */
      var _this$state = _this.state,
          activeIndex = _this$state.activeIndex,
          children = _this$state.children;

      if (activeIndex < 0 && activeIndex > children.length - 1) {
        console.warn('[@collab-ui/react] ButtonGroup: activeIndex is out of bound');
        return;
      }

      var initialActive = _this.getNewIndex(activeIndex - 1, 1);

      _this.setActiveIndex(initialActive);
      /* eslint-enable no-console */

    };

    _this.setFocusIndex = function (index) {
      var focusIndex = _this.state.focusIndex;
      return focusIndex !== index && _this.setState({
        focusIndex: index
      });
    };

    _this.setActiveIndex = function (index) {
      var activeIndex = _this.state.activeIndex;
      return activeIndex !== index && _this.setState({
        activeIndex: index
      });
    };

    _this.handleClick = function (event, index) {
      var onSelect = _this.props.onSelect;

      _this.setFocusIndex(index);

      _this.setActiveIndex(index);

      onSelect && onSelect(event, index);
    };

    _this.getNewIndex = function (currentIndex, change) {
      var children = _this.props.children;
      var length = children.length - 1;

      var getPossibleIndex = function getPossibleIndex() {
        if (currentIndex + change < 0) {
          return length;
        } else if (currentIndex + change > length) {
          return 0;
        }

        return currentIndex + change;
      };

      var possibleIndex = getPossibleIndex();
      var potentialTarget = React.Children.toArray(children)[possibleIndex];
      return potentialTarget.props.disabled ? _this.getNewIndex(possibleIndex, change) : possibleIndex;
    };

    _this.getIncludesFirstCharacter = function (str, char) {
      return str.charAt(0).toLowerCase().includes(char);
    };

    _this.setFocusByFirstCharacter = function (char, currentIdx) {
      var children = _this.props.children;
      var length = children.length - 1;
      var newIndex = React.Children.toArray(children).reduce(function (agg, child, idx, arr) {
        var index = currentIdx + idx + 1 > length ? Math.abs(currentIdx + idx - length) : currentIdx + idx + 1;
        var label = typeof arr[index].props.children === 'string' ? arr[index].props.children : '';
        return !agg.length && !arr[index].props.disabled && !arr[index].props.isReadOnly && _this.getIncludesFirstCharacter(label, char) ? agg.concat(index) : agg;
      }, []);
      !isNaN(newIndex[0]) && _this.setFocusIndex(newIndex[0]);
    };

    _this.handleKeyDown = function (e, idx) {
      var newIndex;
      var flag = false;
      var char = e.key;

      var isPrintableCharacter = function isPrintableCharacter(str) {
        return str.length === 1 && str.match(/\S/);
      };

      switch (e.which) {
        case 38:
        case 37:
          newIndex = _this.getNewIndex(idx, -1);

          _this.setFocusIndex(newIndex);

          flag = true;
          break;

        case 39:
        case 40:
          newIndex = _this.getNewIndex(idx, 1);

          _this.setFocusIndex(newIndex);

          flag = true;
          break;

        default:
          if (isPrintableCharacter(char)) {
            _this.setFocusByFirstCharacter(char, idx);

            flag = true;
          }

          break;
      }

      if (flag) {
        e.stopPropagation();
        e.preventDefault();
      }
    };

    return _this;
  }

  var _proto = ButtonGroup.prototype;

  _proto.componentWillMount = function componentWillMount() {
    if (!this.verifyChildren()) {
      throw new Error('ButtonGroup should only contain Buttons as children.');
    }
  };

  _proto.componentDidMount = function componentDidMount() {
    var _this$state2 = this.state,
        focusIndex = _this$state2.focusIndex,
        activeIndex = _this$state2.activeIndex;
    var initialFocus = this.getNewIndex(focusIndex - 1, 1);
    this.setFocusIndex(initialFocus);
    activeIndex !== null && this.determineInitialActive();
  };

  _proto.render = function render() {
    var _this$props = this.props,
        ariaLabel = _this$props.ariaLabel,
        children = _this$props.children,
        className = _this$props.className,
        highlightSelected = _this$props.highlightSelected,
        justified = _this$props.justified,
        pillWidth = _this$props.pillWidth,
        theme = _this$props.theme,
        type = _this$props.type;
    var activeIndex = this.state.activeIndex;

    var setButtons = function setButtons() {
      return React.Children.map(children, function (child, idx) {
        return React.cloneElement(child, {
          active: type === 'pill' ? false : highlightSelected && activeIndex === idx,
          index: idx,
          className: child.props.children.type && child.props.children.type.displayName === 'Icon' ? 'cui-button--icon-group' : '',
          style: Object.assign({}, pillWidth && {
            width: pillWidth
          })
        });
      });
    };

    return React.createElement("div", {
      className: 'cui-button-group' + ("" + (theme && " cui-button-group--" + theme || '')) + ("" + (justified && " cui-button-group--justified" || '')) + ("" + (type && " cui-button-group--" + type || '')) + ("" + (className && " " + className || '')),
      role: "group",
      "aria-label": ariaLabel
    }, setButtons());
  };

  return ButtonGroup;
}(React.Component);

ButtonGroup.displayName = 'ButtonGroup';
ButtonGroup.childContextTypes = {
  handleClick: PropTypes.func,
  handleKeyDown: PropTypes.func,
  focusIndex: PropTypes.number,
  focusOnLoad: PropTypes.bool
};
ButtonGroup.propTypes = {
  activeIndex: PropTypes.number,
  ariaLabel: PropTypes.string,
  children: PropTypes.node,
  className: PropTypes.string,
  focusOnLoad: PropTypes.bool,
  highlightSelected: PropTypes.bool,
  justified: PropTypes.bool,
  onSelect: PropTypes.func,
  pillWidth: PropTypes.string,
  theme: PropTypes.oneOf(['', 'dark']),
  type: PropTypes.oneOf(['', 'pill'])
};
ButtonGroup.defaultProps = {
  activeIndex: null,
  ariaLabel: '',
  children: null,
  className: '',
  focusOnLoad: false,
  highlightSelected: true,
  justified: true,
  pillWidth: '60px',
  onSelect: null,
  theme: '',
  type: ''
};
export default ButtonGroup;
/**
* @name Default Button Group
*
* @category containers
* @component button-group
* @section default
*
* @js
*
 import { Button } from '@collab-ui/react';

 export default class DefaultButtonGroup extends React.PureComponent {

  render() {
    return(
    <div className='columns large'>
      <ButtonGroup>
        <Button ariaLabel='1'>one</Button>
        <Button ariaLabel='2' disabled>two</Button>
        <Button ariaLabel='3'>three</Button>
      </ButtonGroup>
    </div>
    );
  }
}
**/

/**
* @name Button Groups used in SpaceList
*
* @category containers
* @component button-group
* @section dark
*
* @js
*
 import { Button } from '@collab-ui/react';

 export default class SpaceListButtonGroup extends React.PureComponent {

  render() {
    return(
    <div className='columns large' style={{background: 'black', padding: '20px'}}>
      <ButtonGroup theme="dark">
        <Button ariaLabel='Spaces'>Spaces</Button>
        <Button ariaLabel='Messages'>Messages</Button>
      </ButtonGroup>
    </div>
    );
  }
}
**/

/**
* @name Button Groups with highlightSelected=false
*
* @category containers
* @component button-group
* @section highlightSelected
*
* @js
*
 import { Button, Icon } from '@collab-ui/react';

 export default class CalendarButtonGroup extends React.PureComponent {

  render() {
    return(
    <div className='columns small-3'>
      <ButtonGroup justified={false} highlightSelected={false}>
        <Button ariaLabel='Left'><Icon name='icon-arrow-left_12' /></Button>
        <Button ariaLabel='Today'>Today</Button>
        <Button ariaLabel='Right'><Icon name='icon-arrow-right_12' /></Button>
      </ButtonGroup>
    </div>
    );
  }
}
**/

/**
* @name Icons within Button Group
*
* @category containers
* @component button-group
* @section icons
*
* @js
*
 import { Button, Icon } from '@collab-ui/react';

 export default class IconButtonGroup extends React.PureComponent {

  render() {
    return(
    <div>
      <div className='columns small-4'>
        <ButtonGroup>
          <Button ariaLabel='left'><Icon name='icon-arrow-left_12' /></Button>
          <Button ariaLabel='right'><Icon name='icon-arrow-right_12' /></Button>
        </ButtonGroup>
      </div>
      <div className='columns small-4'>
        <ButtonGroup type='pill'>
          <Button ariaLabel='left'><Icon name='icon-flag_16' /></Button>
          <Button ariaLabel='right'><Icon name='icon-cancel_16' /></Button>
        </ButtonGroup>
      </div>
      <div className='columns small-4'>
        <ButtonGroup type='pill' pillWidth='60px'>
          <Button ariaLabel='left'><Icon name='icon-flag_16' /></Button>
        </ButtonGroup>
      </div>
    </div>
    );
  }
}
**/

/**
* @name Button Groups with justified false
*
* @category containers
* @component button-group
* @section justified
*
* @js
*
 import { Button } from '@collab-ui/react';

 export default class NonJustifiedButtonGroup extends React.PureComponent {

  render() {
    return(
    <div className='columns large'>
      <ButtonGroup justified={false}>
        <Button ariaLabel='1'>one</Button>
        <Button ariaLabel='2' disabled>two</Button>
        <Button ariaLabel='3'>three</Button>
      </ButtonGroup>
    </div>
    );
  }
}
**/