'use strict';

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

var _rollupPluginBabelHelpers = require('../../../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var Combobox_tokens = require('../Combobox.tokens.js');
var pathReducer = require('../reducers/pathReducer.js');
var treePathReducer = require('../reducers/treePathReducer.js');
var focusedPathReducer = require('../reducers/focusedPathReducer.js');
var getTextValue = require('../utils/getTextValue.js');

var useListState = function useListState(_ref) {
  var disabled = _ref.disabled,
    readOnly = _ref.readOnly,
    onToggle = _ref.onToggle,
    multiple = _ref.multiple,
    alwaysOpened = _ref.alwaysOpened,
    renderValue = _ref.renderValue,
    rootRef = _ref.rootRef,
    value = _ref.value,
    valueToItemMap = _ref.valueToItemMap,
    setTextValue = _ref.setTextValue;
  var _useReducer = React.useReducer(pathReducer.pathReducer, alwaysOpened ? ['root'] : []),
    _useReducer2 = _rollupPluginBabelHelpers.slicedToArray(_useReducer, 2),
    path = _useReducer2[0],
    dispatchPath = _useReducer2[1];
  var _useReducer3 = React.useReducer(treePathReducer.treePathReducer, {}),
    _useReducer4 = _rollupPluginBabelHelpers.slicedToArray(_useReducer3, 2),
    treePath = _useReducer4[0],
    dispatchTreePath = _useReducer4[1];
  var _useReducer5 = React.useReducer(focusedPathReducer.focusedPathReducer, []),
    _useReducer6 = _rollupPluginBabelHelpers.slicedToArray(_useReducer5, 2),
    focusedPath = _useReducer6[0],
    dispatchFocusedPath = _useReducer6[1];
  var resetListState = function resetListState() {
    dispatchFocusedPath({
      type: 'reset'
    });
    dispatchPath({
      type: 'reset'
    });
    dispatchTreePath({
      type: 'reset'
    });
  };
  var handleListToggle = function handleListToggle(opened) {
    if (disabled || readOnly) {
      return;
    }
    if (opened) {
      dispatchPath({
        type: 'opened_first_level'
      });
    } else {
      var _rootRef$current;
      resetListState();
      setTextValue(getTextValue.getTextValue(multiple, value, valueToItemMap, renderValue));
      var chipsWrapperNode = rootRef === null || rootRef === void 0 || (_rootRef$current = rootRef.current) === null || _rootRef$current === void 0 ? void 0 : _rootRef$current.querySelector(".".concat(Combobox_tokens.classes.inputScrollableWrapper));
      if (multiple && chipsWrapperNode) {
        chipsWrapperNode.scrollLeft = 0;
      }
    }
    if (onToggle) {
      onToggle(opened);
    }
  };
  return {
    path: path,
    treePath: treePath,
    focusedPath: focusedPath,
    dispatchPath: dispatchPath,
    dispatchTreePath: dispatchTreePath,
    dispatchFocusedPath: dispatchFocusedPath,
    handleListToggle: handleListToggle,
    resetListState: resetListState,
    isListOpened: Boolean(path[0])
  };
};

exports.useListState = useListState;
