import { List } from 'immutable';

import { getEndpointUrl } from '../api/index.js';

import {
  AUCTIONS_UPDATED,
  ITEMS_LOADED,
} from '../constants/actionTypes.js';

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

import Auction from '../domain/Auction.js';


const autionStatusLoadSuccess = (auctions, dispatch) => {
  const payload = List(auctions).map((i) => Auction.fromJS(i));
  dispatch({ type: AUCTIONS_UPDATED, payload });
  dispatch(unblockUI);
};

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

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

  dispatch(blockUI());

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

