import { types } from "../actions/actionTypes";

const initialState = {
  searchDatas: {},
  totalCount: {},
  searchPerformed: false,
  initPerformed: false,
  searchTimestamp: null,
};

export const searchReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.GET_SEARCH: {
      const newResults = action.payload.data.result.results;

      const updatedSearchDatas = action.append ? { ...state.searchDatas } : {};
      newResults.forEach(({ type, docs }) => {
        if (action.append && updatedSearchDatas[type]) {
          for (let i = 0; i < docs.length; i++) {
            updatedSearchDatas[type][action.startIndex + i] = docs[i];
          }
        } else {
          updatedSearchDatas[type] = docs;
        }
      });
      const updatedTotalCount = action.append ? { ...state.totalCount } : {};
      newResults.forEach(({ type, total_count }) => {
        updatedTotalCount[type] = total_count;
      });

      return {
        ...state,
        searchDatas: updatedSearchDatas,
        totalCount: updatedTotalCount,
        searchPerformed: true,
        initPerformed: !action.append,
      };
    }

    case types.RESET_SEARCH:
      return {
        ...initialState,
      };

    case types.SET_SEARCH_INIT_PERFORMED:
      return {
        ...state,
        initPerformed: action.payload,
      };

    case types.UPDATE_SEARCH_TIMESTAMP:
      return {
        ...state,
        searchTimestamp: Date.now(),
      };

    default:
      return state;
  }
};
