import React from "react";
import { SearchResultsStore } from "searchResults/domain/searchStore";
import { RootState, useAppDispatch, useAppSelector } from "store";
import { changeSearchRequestAction, SearchAction } from "./actions/searchActions";
import { SearchStoreState } from "./searchReducer";

const searchSelector = (state: RootState): SearchStoreState =>
  state.searchResults;

const useSearchStoreImplementation = (): SearchResultsStore => {
  const { searchResults, failure, isFailed, isLoading, searchRequest} =
    useAppSelector(searchSelector);

  const dispatch = useAppDispatch();

  const search = React.useCallback(
    (searchRequest: string) => SearchAction(searchRequest)(dispatch),
    [dispatch]
  );
  const changeSearchRequest = React.useCallback(
      (searchRequest: string) => changeSearchRequestAction(searchRequest)(dispatch), [dispatch]
  )

  return {
    isLoading,
    isFailed,
    searchResults,
    failure,
    searchRequest,
    changeSearchRequest: changeSearchRequest,
    search: search,
  };
};

export { useSearchStoreImplementation };
