'use strict';

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

var _rollupPluginBabelHelpers = require('../../../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var pathReducer = require('../reducers/pathReducer.js');
var focusedPathReducer = require('../reducers/focusedPathReducer.js');
var useOutsideClick = require('../../../hooks/useOutsideClick.js');

/**
 * Хук для управления логикой открытия/закрытия выпадающего списка.
 */
var useList = function useList(_ref) {
  var alwaysOpened = _ref.alwaysOpened,
    disabled = _ref.disabled,
    onToggle = _ref.onToggle,
    closeOnOverlayClick = _ref.closeOnOverlayClick,
    floatingPopoverRef = _ref.floatingPopoverRef,
    listWrapperRef = _ref.listWrapperRef;
  var initialPath = alwaysOpened ? ['root'] : [];
  var _useReducer = React.useReducer(pathReducer.pathReducer, initialPath),
    _useReducer2 = _rollupPluginBabelHelpers.slicedToArray(_useReducer, 2),
    path = _useReducer2[0],
    dispatchPath = _useReducer2[1];
  var _useReducer3 = React.useReducer(focusedPathReducer.focusedPathReducer, []),
    _useReducer4 = _rollupPluginBabelHelpers.slicedToArray(_useReducer3, 2),
    focusedPath = _useReducer4[0],
    dispatchFocusedPath = _useReducer4[1];

  /* Callback для глобального открытия/закрытия списка */
  var handleGlobalToggle = function handleGlobalToggle(opened, event) {
    if (disabled) {
      return;
    }
    if (alwaysOpened || opened) {
      dispatchPath({
        type: 'opened_first_level'
      });
    } else {
      dispatchFocusedPath({
        type: 'reset'
      });
      dispatchPath({
        type: 'reset'
      });
    }
    if (onToggle) {
      onToggle(opened, event);
    }
  };

  /* Логика работы при клике за пределами выпадающего списка */
  useOutsideClick.useOutsideClick(function (event) {
    if (!path[0] || !closeOnOverlayClick || alwaysOpened) {
      return;
    }
    dispatchPath({
      type: 'reset'
    });
    dispatchFocusedPath({
      type: 'reset'
    });
    if (onToggle) {
      onToggle(false, event);
    }
  }, [floatingPopoverRef, listWrapperRef]);
  return {
    path: path,
    dispatchPath: dispatchPath,
    focusedPath: focusedPath,
    dispatchFocusedPath: dispatchFocusedPath,
    handleGlobalToggle: handleGlobalToggle
  };
};

exports.useList = useList;
