import { URLS } from "../api/apiConfig";
import { TAxios } from "../api/TAxios";
import { SEARCH_DATA_MAX_RESULTS_LIMIT } from "../utils/Config";
import { types } from "./actionTypes";

// Search 통합검색 (IBS) 데이터 조회 IF-LGSP-090
let getSearchKey = null;
let lastSearchedParams = {};
export const getSearch =
  (params, startIndex = 1, key) =>
  (dispatch, getState) => {
    const { service, query, domain } = params;
    if (startIndex === 1) {
      lastSearchedParams = params;
    }
    const maxResults =
      startIndex === 1
        ? SEARCH_DATA_MAX_RESULTS_LIMIT * 2
        : SEARCH_DATA_MAX_RESULTS_LIMIT;

    let currentKey = key;
    const onSuccess = (response) => {
      console.log("getSearch onSuccess: ", response.data);

      if (startIndex === 1) {
        getSearchKey = new Date();
        currentKey = getSearchKey;

        dispatch({
          type: types.GET_SEARCH,
          payload: response.data,
        });

        dispatch(updateSearchTimestamp());
      } else if (getSearchKey === currentKey) {
        dispatch({
          type: types.GET_SEARCH,
          payload: response.data,
          append: true,
          startIndex: startIndex - 1,
        });
      }
    };

    const onFail = (error) => {
      console.error("getSearch onFail: ", error);
    };

    TAxios(
      dispatch,
      getState,
      "post",
      URLS.GET_SEARCH,
      {},
      { service, query, startIndex, maxResults, domain },
      onSuccess,
      onFail
    );
  };
export const continueSearch =
  (key, startIndex = 1) =>
  (dispatch, getState) => {
    const searchDatas = getState().search.searchDatas;
    const totalCount = getState().search.totalCount;
    if (
      (startIndex <= 1 && !searchDatas[key]) ||
      searchDatas[key][startIndex - 1] ||
      !totalCount[key] ||
      totalCount[key] < startIndex
    ) {
      //ignore search
      return;
    }
    dispatch(
      getSearch(
        { ...lastSearchedParams, domain: key },
        startIndex,
        getSearchKey
      )
    );
  };

export const resetSearch = (status) => {
  getSearchKey = null;
  return { type: types.RESET_SEARCH, payload: status };
};

export const setInitPerformed = (performed) => ({
  type: types.SET_SEARCH_INIT_PERFORMED,
  payload: performed,
});

export const updateSearchTimestamp = () => ({
  type: types.UPDATE_SEARCH_TIMESTAMP,
});
