'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _getClassName2 = require('babel-plugin-react-css-modules/dist/browser/getClassName');

var _getClassName3 = _interopRequireDefault(_getClassName2);

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

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

var _styleModuleImportMap = {
  './accordion.scss': {
    'wrapper': 'flive_accordion_wrapper',
    'item': 'flive_accordion_item',
    'item-open': 'flive_accordion_item-open',
    'trigger': 'flive_accordion_trigger',
    'open': 'flive_accordion_open',
    'closed': 'flive_accordion_closed',
    'outer': 'flive_accordion_outer',
    'inner': 'flive_accordion_inner'
  }
};

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 AccordionItem = function (_PureComponent) {
  _inherits(AccordionItem, _PureComponent);

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

    // Defaults the dropdown to be closed
    var _this = _possibleConstructorReturn(this, (AccordionItem.__proto__ || Object.getPrototypeOf(AccordionItem)).call(this, props));

    _this.componentDidUpdate = function (prevProps, prevState) {
      if (_this.state.shouldOpenOnNextCycle) {
        _this.continueOpenCollapsible();
      }

      if (prevState.height === 'auto' && _this.state.shouldSwitchAutoOnNextCycle === true) {
        window.setTimeout(function () {
          // Set small timeout to ensure a true re-render
          _this.setState({
            height: 0,
            overflow: 'hidden',
            isClosed: true,
            shouldSwitchAutoOnNextCycle: false
          });
        }, 50);
      }

      // If there has been a change in the open prop (controlled by accordion)
      if (prevProps.open !== _this.props.open) {
        if (_this.props.open === true) {
          _this.openCollapsible();
        } else {
          _this.closeCollapsible();
        }
      }
    };

    _this.closeCollapsible = function () {
      _this.setState({
        shouldSwitchAutoOnNextCycle: true,
        height: _this.inner.offsetHeight,
        transition: 'height ' + _this.props.transitionTime + 'ms ' + _this.props.easing,
        inTransition: true
      });
    };

    _this.openCollapsible = function () {
      _this.setState({
        inTransition: true,
        shouldOpenOnNextCycle: true
      });
    };

    _this.continueOpenCollapsible = function () {
      _this.setState({
        height: _this.inner.offsetHeight,
        transition: 'height ' + _this.props.transitionTime + 'ms ' + _this.props.easing,
        isClosed: false,
        hasBeenOpened: true,
        inTransition: true,
        shouldOpenOnNextCycle: false
      });
    };

    _this.handleTriggerClick = function (event) {
      event.preventDefault();

      if (_this.props.triggerDisabled) {
        return;
      }

      if (_this.props.handleTriggerClick) {
        _this.props.handleTriggerClick(_this.props.accordionPosition);
      } else {
        if (_this.state.isClosed === true) {
          _this.openCollapsible();
          _this.props.onOpening();
        } else {
          _this.closeCollapsible();
          _this.props.onClosing();
        }
      }
    };

    _this.handleTransitionEnd = function () {
      // Switch to height auto to make the container responsive
      if (!_this.state.isClosed) {
        _this.setState({ height: 'auto', overflow: _this.props.overflowWhenOpen, inTransition: false });
        _this.props.onOpen();
      } else {
        _this.setState({ inTransition: false });
        _this.props.onClose();
      }
    };

    if (props.open) {
      _this.state = {
        isClosed: false,
        shouldSwitchAutoOnNextCycle: false,
        height: 'auto',
        transition: 'none',
        hasBeenOpened: true,
        overflow: props.overflowWhenOpen,
        inTransition: false
      };
    } else {
      _this.state = {
        isClosed: true,
        shouldSwitchAutoOnNextCycle: false,
        height: 0,
        transition: 'height ' + props.transitionTime + 'ms ' + props.easing,
        hasBeenOpened: false,
        overflow: 'hidden',
        inTransition: false
      };
    }
    return _this;
  }

  _createClass(AccordionItem, [{
    key: 'render',
    value: function render() {
      var _this2 = this;

      var dropdownStyle = {
        height: this.state.height,
        WebkitTransition: this.state.transition,
        msTransition: this.state.transition,
        transition: this.state.transition,
        overflow: this.state.overflow
      };

      // If user wants different text when tray is open
      var trigger = this.state.isClosed === false && this.props.triggerWhenOpen !== undefined ? this.props.triggerWhenOpen : this.props.trigger;

      // Don't render children until the first opening of the Collapsible if lazy rendering is enabled
      var children = this.props.lazyRender && !this.state.hasBeenOpened && this.state.isClosed && !this.state.inTransition ? null : this.props.children;

      var triggerStyleName = (0, _classnames2.default)('trigger', {
        closed: this.state.isClosed,
        open: !this.state.isClosed,
        disabled: this.props.triggerDisabled
      });

      return _react2.default.createElement(
        'div',
        {
          className: (this.props.className ? this.props.className + ' ' : '') + (0, _getClassName3.default)((0, _classnames2.default)('item', { 'item-open': !this.state.isClosed }), _styleModuleImportMap)
        },
        _react2.default.createElement(
          'a',
          {
            onClick: this.handleTriggerClick,
            href: '#',
            className: (0, _getClassName3.default)(triggerStyleName, _styleModuleImportMap)
          },
          trigger
        ),
        _react2.default.createElement(
          'div',
          {
            className: 'flive_accordion_outer',
            ref: function ref(_ref2) {
              return _this2.outer = _ref2;
            },
            style: dropdownStyle,
            onTransitionEnd: this.handleTransitionEnd
          },
          _react2.default.createElement(
            'div',
            {
              className: 'flive_accordion_inner',
              ref: function ref(_ref) {
                return _this2.inner = _ref;
              }
            },
            children
          )
        )
      );
    }
  }]);

  return AccordionItem;
}(_react.PureComponent);

AccordionItem.propTypes = {
  /** @ignore */
  className: _propTypes2.default.string,
  transitionTime: _propTypes2.default.number,
  easing: _propTypes2.default.string,
  open: _propTypes2.default.bool,
  accordionPosition: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  handleTriggerClick: _propTypes2.default.func,
  onOpen: _propTypes2.default.func,
  onClose: _propTypes2.default.func,
  onOpening: _propTypes2.default.func,
  onClosing: _propTypes2.default.func,
  trigger: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.element]),
  triggerWhenOpen: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.element]),
  triggerDisabled: _propTypes2.default.bool,
  lazyRender: _propTypes2.default.bool,
  overflowWhenOpen: _propTypes2.default.oneOf(['hidden', 'visible', 'auto', 'scroll', 'inherit', 'initial', 'unset'])
};

AccordionItem.defaultProps = {
  className: undefined,
  transitionTime: 200,
  easing: 'linear',
  open: false,
  triggerDisabled: false,
  lazyRender: false,
  overflowWhenOpen: 'hidden',
  onOpen: function onOpen() {},
  onClose: function onClose() {},
  onOpening: function onOpening() {},
  onClosing: function onClosing() {}
};

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