import {
  OFFERS_ADD,
  OFFERS_CLEAR,
  OFFERS_ERROR,
  OFFERS_MINE_SET,
  OFFERS_NO_MORE,
  OFFERS_PINNED_ADD,
  OFFERS_PINNED_SET,
  OFFERS_SET,
  OFFER_ADD,
  OFFER_SET,
  ONE_OFFER_FETCH,
  ONE_OFFER_ERROR,
  ONE_OFFER_SUCCESS,
  OFFERS_SET_TOTAL,
  OFFERS_PROFILE_SET,
} from "../../actions/offers/offersActionConstants";
import createReducer from "../../utils/createReducer";

const initialState = {
  offers: [],
  pinnedOffers: [],
  mineOffers: [],
  profileOffers: [],
  total: 0,
  error: "",
  newOffer: "",
  selectedOffer:"",
  noMoreOffers: false,
};

export default createReducer(
  {
    [OFFERS_ERROR]: fetchOffersError,
    [OFFERS_CLEAR]: clearOffers,
    [OFFERS_SET]: setOffers,
    [OFFERS_ADD]: addOffers,
    [OFFER_ADD]: addOffer,
    [OFFER_SET]: setOffer,
    [ONE_OFFER_ERROR]: fetchOneOfferError,
    [ONE_OFFER_SUCCESS]: fetchOneOfferSuccess,
    [ONE_OFFER_FETCH]: fetchOneOffer,
    [OFFERS_NO_MORE]: setNoMoreOffersStatus,
    [OFFERS_PINNED_ADD]: addPinnedOffers,
    [OFFERS_PINNED_SET]: setPinnedOffers,
    [OFFERS_SET_TOTAL]: setTotalOffers,
    [OFFERS_MINE_SET]: setMineOffers,
    [OFFERS_PROFILE_SET]: setProfileOffers,
  },
  initialState
);

function fetchOffersError(state, action) {
  return { ...state, error: action.payload };
}

function clearOffers() {
  return initialState;
}
function setOffers(state, action) {
  return {
    ...state,
    offers: action.payload,
  };
}
function setOffer(state, action) {
  return {
    ...state,
    selectedOffer: action.payload,
  };
}
function addOffers(state, action) {
  return {
    ...state,
    offers: [...state.offers, ...action.payload]
  }
}
function setPinnedOffers(state, action) {
  return {
    ...state,
    pinnedOffers: [...action.payload]
  }
}
function addOffer(state, action) {
  return {
    ...state,
    offer: action.payload
  }
}

function fetchOneOffer(state,action) {
  return {
    ...state,
    selectedOffer: action.payload
  }
}
function fetchOneOfferSuccess( state, action) {
  return {
    ...state,
    selectedOffer: action.payload
  }
}
function fetchOneOfferError (state, action) {
  return {
    ...state,
    error: action.payload
  }
}
function addPinnedOffers(state, action) {
  return {
    ...state,
    pinnedOffers: [...state.pinnedOffers, ...action.payload]
  }
}
function setNoMoreOffersStatus(state, action) {
  return {
    ...state,
    noMoreOffers: action.payload
  }
}
function setTotalOffers(state, action) {
  return {
    ...state,
    total: action.payload
  }
}
function setMineOffers(state, action) {
  return {
    ...state,
    mineOffers: action.payload
  }
}
function setProfileOffers(state, action) {
  return {
    ...state,
    profileOffers: action.payload
  }
}
