'use strict';

exports.__esModule = true;

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

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _helper = require('./Shared/helper.js');

var _CCollapseCustom = require('./CCollapseCustom');

var _CCollapseCustom2 = _interopRequireDefault(_CCollapseCustom);

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

//component - CoreUI / CCollapse

var omitKeys = ['toggleEvents', 'defaultOpen', 'custom'];

var CCollapse = function CCollapse(props) {
  var custom = props.custom,
      toggle = props.toggle,
      show = props.show;

  var _useState = (0, _react.useState)(props.defaultOpen || false),
      isOpen = _useState[0],
      setIsOpen = _useState[1];

  var fields = (0, _react.useRef)({
    togglers: null,
    removeEventListeners: null
  }).current;

  if (!custom) {
    show = isOpen;
    var userToggle = toggle;
    toggle = function toggle(e) {
      setIsOpen(!isOpen);
      e.preventDefault();
      if (userToggle) userToggle(e);
    };
  }

  //effect

  (0, _react.useEffect)(function () {
    if (custom) return;
    fields.togglers = (0, _helper.findDOMElements)(props.toggler);
    if (fields.togglers.length) {
      fields.removeEventListeners = (0, _helper.addMultipleEventListeners)(fields.togglers, toggle, props.toggleEvents);
    }
    return function cleanup() {
      if (fields.togglers.length && fields.removeEventListeners) {
        fields.removeEventListeners();
      }
    };
  });

  //render

  return _react2.default.createElement(_CCollapseCustom2.default, _extends({ show: show }, (0, _helper.omit)(props, omitKeys)));
};

CCollapse.propTypes = process.env.NODE_ENV !== "production" ? {
  custom: _propTypes2.default.bool,
  //
  innerRef: _propTypes2.default.oneOfType([_propTypes2.default.object, _propTypes2.default.func, _propTypes2.default.string]),
  defaultOpen: _propTypes2.default.bool,
  toggler: _propTypes2.default.string,
  toggleEvents: _propTypes2.default.arrayOf(_propTypes2.default.string)
} : {};

CCollapse.defaultProps = {
  toggleEvents: _helper.defaultToggleEvents
};

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