import { ref } from 'vue';
import { isFunction } from 'lodash-es';

var useFilter = (props, allKeys, nodeList) => {
  const filteredKeys = ref([]);
  const filteredExpandedKeys = ref([]);
  const isSearchingRef = ref(false);
  function traverse(filterMethod, filterText) {
    const _filteredExpandedKeys = [];
    const _filteredKeys = [];
    const _filteredExpandedKeysMap = new Map();
    const _filteredKeysMap = new Map();
    allKeys.value.forEach(key => {
      const node = nodeList.get(key);
      if (filterMethod(filterText, node)) {
        const parentKeys = node.indexPath;
        parentKeys.forEach(_key => {
          if (!_filteredExpandedKeysMap.get(_key)) {
            _filteredExpandedKeys.push(_key);
            _filteredExpandedKeysMap.set(_key, true);
          }
          if (!_filteredKeysMap.get(_key)) {
            _filteredKeys.push(_key);
            _filteredKeysMap.set(_key, true);
          }
        });
      }
    });
    _filteredExpandedKeysMap.clear();
    _filteredKeysMap.clear();
    return [_filteredExpandedKeys, _filteredKeys];
  }
  const filter = filterText => {
    const filterMethod = props.filterMethod;
    if (!isFunction(filterMethod)) {
      return;
    }
    if (filterText) {
      const [_filteredExpandedKeys, _filteredKeys] = traverse(filterMethod, filterText);
      filteredExpandedKeys.value = _filteredExpandedKeys;
      filteredKeys.value = _filteredKeys;
    } else {
      filteredExpandedKeys.value = [];
      filteredKeys.value = [];
    }
    isSearchingRef.value = !!filterText;
  };
  return {
    filteredKeys,
    filteredExpandedKeys,
    filter,
    isSearchingRef
  };
};

export { useFilter as default };
