import { blockUI, unblockUI } from './index.js';

import {
  BID_FAILURE,
  BID_SUCCESS,
  PLACE_BID,
  SET_AUCTION_FILTER,
  SET_AUCTION_VIEW_MODE,
} from '../constants/actionTypes.js';

const placeBidFailure = (bid, dispatch) => {
  dispatch({ type: BID_FAILURE, bid });
  dispatch(unblockUI);
};

const placeBidSuccess = (bid, dispatch) => {
  dispatch({ type: BID_SUCCESS, bid });
  dispatch(unblockUI);
};

export const changeFilterMode = (payload) => ({
  type: SET_AUCTION_FILTER,
  payload,
});

export const changeViewMode = (payload) => ({
  type: SET_AUCTION_VIEW_MODE,
  payload,
});

export const placeBid = (payload) => ({
  type: PLACE_BID,
  payload,
});

export const postBid = () => (dispatch, getState) => {
  const state = getState();
  const activeEvent = state.get('activeEvent');

  let apiUrl = getEndpointUrl(API_ENDPOINTS.GET_ITEMS);
  apiUrl = apiUrl.replace(/:event_id$/, '');
  if (activeEvent) {
    apiUrl = `${apiUrl}${activeEvent}`;
  }

  dispatch(blockUI());

  fetch(apiUrl)
    .then(response => response.json())
    .then(payload => itemsLoadSuccess(payload, dispatch))
    .catch(err => console.error('[actions::getItems]', err));
};
