import * as actionTypes from "./searchActionTypes";
import { search } from "../searchService";
import { dispatchStatus } from "store";
import Failure from "core/failure";

const SearchAction = (query: string) => (dispatch: any) => {
  dispatch({ type: actionTypes.GET_SEARCH_RESULTS });

  return search(query)
    .then((searchResult) => {
      dispatchStatus(
        actionTypes.GET_SEARCH_RESULTS,
        ".success",
        searchResult
      )(dispatch);
      return searchResult;
    })
    .catch((failure: Failure) => {
      dispatchStatus(
        actionTypes.GET_SEARCH_RESULTS,
        ".failure",
        failure
      )(dispatch);
      return undefined;
    });
};
const changeSearchRequestAction =
  (searchRequest: string) => (dispatch: any) => {
    dispatch({ type: actionTypes.CHANGE_SEARCH_REQUEST, searchRequest });
  };

export { SearchAction, changeSearchRequestAction };
