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

import React, { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { omit, findDOMElements, defaultToggleEvents, addMultipleEventListeners } from './Shared/helper.js';
import CCollapseCustom from './CCollapseCustom';

//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 = useState(props.defaultOpen || false),
      isOpen = _useState[0],
      setIsOpen = _useState[1];

  var fields = 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

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

  //render

  return React.createElement(CCollapseCustom, _extends({ show: show }, omit(props, omitKeys)));
};

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

CCollapse.defaultProps = {
  toggleEvents: defaultToggleEvents
};

export default CCollapse;