import React, { useState } from "react";
import { on_select, on_remove, // get_selected_suggestion,
add, filter_options_check } from "../utils/MultiSelect.manage";
import multiSelectStateReducers from "../actions/MultiSelect.action";
import useCommonReducer from "../../../libraries/reducerHandler";
import constants from "../actions/MultiSelect.actionConstants";
export default function useMultiSelect(props, reducer) {
  let {
    state = {},
    dispatch
  } = useCommonReducer(multiSelectStateReducers, reducer, {
    selectedSuggestions: [],
    filteredOptions: [],
    list: []
  });

  function onHandleSelect(value) {
    on_select(value, state);
    let selected_suggestions = state.selectedSuggestions;
    let newState = { ...state,
      selectedSuggestions: selected_suggestions
    };
    dispatch({
      type: constants.ON_MULTISELECT_SELECT,
      data: newState
    });
  }

  function addValue(obj) {
    add(obj, state);
    dispatch({
      type: constants.ON_MULTISELECT_ADD,
      data: state
    });
  }

  function get_data() {
    return state.list;
  }

  function get_filtered_options_data() {
    return state.filteredOptions;
  }

  function get_selected_suggestion() {
    return state.selectedSuggestions;
  }

  function filterOptionsCheck(value) {
    return filter_options_check(value, state.filteredOptions);
  }

  function updateSelectedValues(value) {
    let {
      selectedSuggestions,
      filteredOptions,
      list
    } = state.selectedSuggestions;
    dispatch({
      type: constants.ON_MULTISELECT_UPDATE_SELECTED_VALUES,
      data: value
    });
  }

  function onHandleRemove(value) {
    on_remove(value, state);
    let selected_suggestions = state.selectedSuggestions;
    let newState = { ...state,
      selectedSuggestions: selected_suggestions
    };
    dispatch({
      type: constants.ON_MULTISELECT_REMOVE,
      data: newState
    });
  }

  function shotcutKeys(e, value) {
    const {
      keyCode,
      ctrlKey,
      metaKey,
      shiftKey
    } = e;

    if (keyCode === 8 || keyCode === 46) {
      let selected_suggestions = state.selectedSuggestions;
      let index = selected_suggestions.findIndex((ele, i) => {
        if (ele == value) {
          return i;
        }
      });
      let val = index > -1 ? selected_suggestions[index] : selected_suggestions.pop();
      on_remove(val, state);
      selected_suggestions = state.selectedSuggestions;
      dispatch({
        type: constants.ON_MULTISELECT_REMOVE,
        data: state
      });
    }
  }

  return {
    selectedValues: state.selectedSuggestions,
    onHandleSelect,
    onHandleRemove,
    updateSelectedValues,
    shotcutKeys,
    addOptions: addValue,
    filterOptionsCheck,
    list: state.list,
    getFilteredOptionsData: get_filtered_options_data()
  };
}