'use strict';

exports.__esModule = true;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _Collapse = require('../../animations/Collapse');

var _Collapse2 = _interopRequireDefault(_Collapse);

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

var _Icon2 = _interopRequireDefault(_Icon);

var _Paragraph = require('../../atoms/text/Paragraph');

var _Paragraph2 = _interopRequireDefault(_Paragraph);

require('./style.css');

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

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; }

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

  function HelpTip(props) {
    _classCallCheck(this, HelpTip);

    var _this = _possibleConstructorReturn(this, _Component.call(this, props));

    _this.getSplitText = function (text, triggers) {
      var splitText = text;
      triggers.forEach(function (trigger, index) {
        if (index === 0) {
          splitText = splitText.split(trigger);
        } else {
          var nextPart = splitText[index].split(trigger);
          splitText.pop();
          splitText = splitText.concat(nextPart);
        }
      });
      return splitText;
    };

    _this.toggleOpenForKeyUp = function (e, index) {
      if (e.which === 13 || e.which === 32) {
        // 13 is enter, 32 is spacebar
        e.preventDefault();
        e.stopPropagation();
        _this.toggleOpen(index);
      }
    };

    _this.toggleOpen = function (index) {
      var isOpen = _this.state.isOpen;

      isOpen[index] = !_this.state.isOpen[index];
      _this.setState({ isOpen: isOpen });
    };

    _this.buildDangerouslyIfHasMarkup = function (text, hasMarkup) {
      return (
        /* eslint-disable react/no-danger */
        hasMarkup ? _react2.default.createElement('span', { dangerouslySetInnerHTML: { __html: text } }) : text
      );
    };

    var openArray = _this.props.triggerText.map(function () {
      return false;
    });
    _this.state = {
      isOpen: openArray
    };
    return _this;
  }

  HelpTip.prototype.render = function render() {
    var _classNames,
        _classNames2,
        _classNames3,
        _classNames4,
        _this2 = this;

    var _props = this.props,
        hasMarkup = _props.hasMarkup,
        triggerText = _props.triggerText,
        helpText = _props.helpText,
        children = _props.children,
        id = _props.id,
        theme = _props.theme,
        text = _props.text,
        disabled = _props.disabled;


    var baseClass = (0, _classnames2.default)((_classNames = {
      'ma__help-tip': true,
      'mobile-tray': !this.props.bypassMobileStyle
    }, _classNames['ma__help-tip__text--' + theme] = theme, _classNames));
    var helpTextClasses = (0, _classnames2.default)((_classNames2 = {
      'ma__help-tip__text': !children,
      'ma__help-tip__text--children': children
    }, _classNames2['ma__help-tip__text--' + theme] = theme, _classNames2));
    var helpTextContainer = (0, _classnames2.default)((_classNames3 = {
      'ma__help-tip__container': true
    }, _classNames3['ma__help-tip__container--' + theme] = theme, _classNames3));
    var helpTextDirect = (0, _classnames2.default)((_classNames4 = {
      'ma__help-tip__text-direct': true
    }, _classNames4['ma__help-tip__text-direct--' + theme] = theme, _classNames4));
    var splitText = this.getSplitText(text, triggerText);
    var childArray = children && (Array.isArray(children) ? children : [children]);

    return _react2.default.createElement(
      'span',
      { className: baseClass, id: id },
      triggerText.map(function (trigger, index) {
        var triggerTextClasses = (0, _classnames2.default)({
          'ma__help-tip__trigger': true,
          'ma__help-tip__trigger--active': _this2.state.isOpen[index],
          'ma__help-tip__trigger--disabled': disabled
        });
        return (
          /* eslint-disable-next-line react/no-array-index-key */
          _react2.default.createElement(
            'span',
            { key: 'help-tip-label-' + id + '-' + index, className: 'ma__help-tip__label', id: 'label-' + id + '-' + index },
            index === 0 && _this2.buildDangerouslyIfHasMarkup(splitText[index], hasMarkup),
            _react2.default.createElement(
              'span',
              { className: 'ma_help-tip__label-a11y', id: 'context-a11y-' + id + '-' + index, 'aria-hidden': 'true' },
              _this2.state.isOpen[index] ? 'Close tooltip info about ' : 'Open tooltip info about ',
              _this2.buildDangerouslyIfHasMarkup(trigger, hasMarkup)
            ),
            _react2.default.createElement(
              'span',
              {
                className: triggerTextClasses,
                id: 'trigger-' + id + '-' + index,
                onClick: function onClick() {
                  return _this2.toggleOpen(index);
                },
                onKeyUp: function onKeyUp(e) {
                  return _this2.toggleOpenForKeyUp(e, index);
                },
                tabIndex: disabled ? -1 : 0,
                role: 'button',
                'aria-describedby': 'context-a11y-' + id + '-' + index,
                'aria-expanded': _this2.state.isOpen[index],
                'aria-controls': 'help-tip-content-' + id + '-' + index
              },
              _this2.buildDangerouslyIfHasMarkup(trigger, hasMarkup),
              _react2.default.createElement(_Icon2.default, { name: 'questionmark', svgHeight: 15, svgWidth: 15 })
            ),
            _this2.buildDangerouslyIfHasMarkup(splitText[index + 1], hasMarkup)
          )
        );
      }),
      triggerText.map(function (trigger, index) {
        return !disabled &&
        /* eslint-disable-next-line react/no-array-index-key */
        _react2.default.createElement(
          _Collapse2.default,
          { key: 'help-tip-collapse-' + id + '-' + index, 'in': _this2.state.isOpen[index], dimension: 'height', className: helpTextContainer },
          _react2.default.createElement(
            'div',
            { className: 'ma__help-tip__content', id: 'help-tip-content-' + id + '-' + index, 'aria-hidden': !_this2.state.isOpen[index] },
            _react2.default.createElement(
              'div',
              {
                tabIndex: '0',
                role: 'button',
                className: 'ma__help-tip__close-mobile',
                onClick: function onClick() {
                  return _this2.toggleOpen(index);
                },
                onKeyUp: function onKeyUp(e) {
                  return _this2.toggleOpenForKeyUp(e, index);
                },
                'aria-label': _this2.state.isOpen[index] && 'Close help tip.'
              },
              _react2.default.createElement(_Icon2.default, { name: 'close' })
            ),
            _react2.default.createElement(
              'div',
              {
                tabIndex: '0',
                role: 'button',
                className: 'ma__help-tip__close-desktop',
                onClick: function onClick() {
                  return _this2.toggleOpen(index);
                },
                onKeyUp: function onKeyUp(e) {
                  return _this2.toggleOpenForKeyUp(e, index);
                },
                'aria-label': _this2.state.isOpen[index] && 'Close help tip.'
              },
              _react2.default.createElement(_Icon2.default, { name: 'close' })
            ),
            (helpText || childArray) && _react2.default.createElement(
              'div',
              { className: helpTextClasses, 'aria-live': 'polite' },
              helpText && helpText[index] && _react2.default.createElement(_Paragraph2.default, { className: helpTextDirect, text: helpText[index] }),
              childArray && childArray[index] && childArray[index]
            )
          )
        );
      })
    );
  };

  return HelpTip;
}(_react.Component);

HelpTip.propTypes = process.env.NODE_ENV !== "production" ? {
  /** The text that will have one or more help tips inserted in it. */
  text: _propTypes2.default.string,
  /** The text that will be a clickable inline toolitp */
  triggerText: _propTypes2.default.arrayOf(_propTypes2.default.string),
  /** The help text that is displayed on clicking the trigger text */
  /** You can also render children in the help text */
  helpText: _propTypes2.default.arrayOf(_propTypes2.default.string),
  /** The id for the whole component */
  id: _propTypes2.default.string.isRequired,
  /** Whether you want the help text to slide up on mobile screens */
  bypassMobileStyle: _propTypes2.default.bool,
  /** Whether text contains html markup */
  hasMarkup: _propTypes2.default.bool,
  /** Themes correspond to site color scheme i.e. sass variables */
  theme: _propTypes2.default.oneOf(['c-primary', 'c-primary-alt', 'c-highlight', 'c-gray-dark', 'c-error-red', 'c-white']),
  /** Disable helptip trigger text */
  disabled: _propTypes2.default.bool,
  children: _propTypes2.default.node
} : {};

HelpTip.defaultProps = {
  hasMarkup: true,
  theme: 'c-primary',
  bypassMobileStyle: false
};

exports.default = HelpTip;
module.exports = exports['default'];