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 _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof 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; }

import React, { Component } from 'react';
import { findDOMNode } from 'react-dom';
import { Box } from 'grommet/es6/components/Box';
import { Text } from 'grommet/es6/components/Text';
import { Keyboard } from 'grommet/es6/components/Keyboard';
import { FormClose } from 'grommet-icons/es6/icons/FormClose';

import { Tag } from '../Tag';

var Tags = function (_Component) {
  _inherits(Tags, _Component);

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

    _classCallCheck(this, Tags);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = {
      selectedTagIndex: -1
    }, _this.tagRefs = [], _this.selectTag = function (selected) {
      var _this$props = _this.props,
          onChange = _this$props.onChange,
          value = _this$props.value;

      if (onChange) {
        var tags = selected;
        if (Array.isArray(value)) {
          var index = value.indexOf(tags);
          if (index !== -1) {
            tags = value.filter(function (item) {
              return item !== selected;
            });
          } else {
            tags = [].concat(value, [tags]);
          }
        } else {
          tags = [tags];
        }
        onChange({ target: findDOMNode(_this.inputRef), option: selected, value: tags });
      }
    }, _this.onNextTag = function (event) {
      var value = _this.props.value;
      var selectedTagIndex = _this.state.selectedTagIndex;

      event.preventDefault();
      var index = selectedTagIndex + 1;
      if (index >= value.length) {
        index = 0;
      }
      _this.focusTag(index);
    }, _this.onPreviousTag = function (event) {
      var selectedTagIndex = _this.state.selectedTagIndex;
      var value = _this.props.value;

      event.preventDefault();
      var index = selectedTagIndex - 1;
      if (index < 0) {
        index = value.length - 1;
      }
      _this.focusTag(index);
    }, _this.onSelectTag = function (event) {
      var value = _this.props.value;
      var selectedTagIndex = _this.state.selectedTagIndex;

      if (selectedTagIndex >= 0 && selectedTagIndex < value.length) {
        event.preventDefault(); // prevent submitting forms
        event.stopPropagation();
        _this.selectTag(value[selectedTagIndex]);
      }
    }, _this.onCloseClick = function (e, tag) {
      e.stopPropagation();
      _this.selectTag(tag);
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  Tags.prototype.focusTag = function focusTag(index) {
    if (index >= 0 && index < this.tagRefs.length) {
      findDOMNode(this.tagRefs[index]).focus();
      this.setState({ selectedTagIndex: index });
    }
  };

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

    var _props = this.props,
        placeholder = _props.placeholder,
        children = _props.children,
        id = _props.id,
        name = _props.name,
        value = _props.value,
        onChange = _props.onChange,
        focusable = _props.focusable,
        onClick = _props.onClick,
        direction = _props.direction,
        icon = _props.icon,
        tagProps = _props.tagProps,
        rest = _objectWithoutProperties(_props, ['placeholder', 'children', 'id', 'name', 'value', 'onChange', 'focusable', 'onClick', 'direction', 'icon', 'tagProps']);

    var noValues = void 0;
    if (!value || Array.isArray(value) && value.length === 0) {
      noValues = React.isValidElement(placeholder) ? placeholder :
      // placeholder. minimum height of icon to keep size
      React.createElement(
        Text,
        { color: 'placeholder', style: { minHeight: '24px' } },
        placeholder || 'No selection'
      );
    }

    var values = void 0;
    if (Array.isArray(value)) {
      values = value;
    } else {
      values = value ? [value] : [];
    }
    return React.createElement(
      Keyboard,
      {
        onEnter: this.onSelectTag,
        onSpace: this.onSelectTag,
        onLeft: this.onPreviousTag,
        onRight: this.onNextTag
      },
      React.createElement(
        Box,
        _extends({
          tabIndex: focusable ? '0' : undefined,
          id: id ? id + '__tag-container' : undefined,
          direction: direction,
          overflow: 'auto',
          style: { minWidth: 'auto' }
        }, rest),
        noValues || values.map(function (tag, index) {
          return children ? children(tag, index, value) : React.createElement(Tag, _extends({
            key: 'tag_' + (name || '') + '_' + index,
            ariaChecked: true,
            a11yTitle: 'Remove ' + tag.toString(),
            label: (typeof tag === 'undefined' ? 'undefined' : _typeof(tag)) !== 'object' ? tag.toString() : undefined,
            ref: function ref(_ref) {
              _this2.tagRefs[index] = _ref;
            },
            onClick: onClick ? function (e) {
              return onClick(e, tag);
            } : undefined,
            onChange: onChange ? function (e) {
              return _this2.onCloseClick(e, tag);
            } : undefined,
            icon: icon
          }, (typeof tag === 'undefined' ? 'undefined' : _typeof(tag)) === 'object' ? _extends({}, tagProps, tag) : tagProps));
        })
      )
    );
  };

  return Tags;
}(Component);

Tags.defaultProps = {
  pad: 'small',
  focusable: true,
  margin: { horizontal: 'xsmall', vertical: 'small' },
  value: [],
  gap: 'xsmall',
  direction: 'row-responsive',
  icon: React.createElement(FormClose, null)
};

var TagsDoc = void 0;
if (process.env.NODE_ENV !== 'production') {
  TagsDoc = require('./doc').default(Tags); // eslint-disable-line global-require
}

var TagsWrapper = TagsDoc || Tags;

export { TagsWrapper as Tags };