import React, { useEffect } from 'react';
import includes from 'lodash/includes';
import Events from '../utils/events';

var Trigger = function Trigger(props) {
  var visible = props.visible,
      onClose = props.onClose,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled; // execute callback function, KeyboardEvent.keycode was not recommended in MDN.

  var onKeydown = function onKeydown(e) {
    if (e.code === 'Escape') {
      var lens = Trigger.instanceList.length;
      var last = Trigger.instanceList[lens - 1];

      if (last) {
        !last.disabled && last();
      }
    }
  };

  useEffect(function () {
    onClose && (onClose.disabled = disabled);

    if (visible === true && typeof onClose === 'function') {
      if (!includes(Trigger.instanceList, onClose)) {
        Trigger.instanceList.push(onClose);
      }
    } else {
      var index = Trigger.instanceList.findIndex(function (c) {
        return c === onClose;
      });

      if (index > -1) {
        Trigger.instanceList.splice(index, 1);
      }
    }
  }, [visible, disabled, onClose]);
  useEffect(function () {
    // In the case of multiple Trigger Components, only execute addEventlistener just for once.
    if (Trigger.count === 0) {
      Events.on(document.body, 'keydown', onKeydown);
    }

    Trigger.count += 1;
    return function () {
      var index = Trigger.instanceList.findIndex(function (c) {
        return c === onClose;
      });

      if (index > -1) {
        Trigger.instanceList.splice(index, 1);
      }

      Trigger.count -= 1;

      if (Trigger.count === 0) {
        Events.off(document.body, 'keydown', onKeydown);
      }
    };
  }, []);
  return /*#__PURE__*/React.createElement(React.Fragment, null, props.children);
};

Trigger.defaultProps = {
  visible: false,
  disabled: false
};
Trigger.instanceList = [];
Trigger.count = 0;
export default Trigger;