import { Queue, CustomEvent } from './queue.type';
import { actionTypes } from 'constants/action-types';

export function setCustomEvents(customEvents) {
  return async (dispatch) => {
    dispatch({
      type: actionTypes.QUEUE_SET_CUSTOM_EVENTS,
      payload: customEvents
    });
  };
}

export function clearCustomEvents() {
  return async (dispatch) => {
    dispatch({
      type: actionTypes.QUEUE_CLEAR_CUSTOM_EVENTS
    });
  };
}

export function addCustomEvent(customEvent: CustomEvent | Queue['customEvents'] = []) {
  return async (dispatch) => {
    const customEvents = Array.isArray(customEvent) ? customEvent : [customEvent];
    dispatch({
      type: actionTypes.QUEUE_ADD_CUSTOM_EVENTS,
      payload: customEvents
    });
  };
}

const initialState: Queue = {
  customEvents: []
};

export default function queueReducer(state = initialState, { type, payload }) {
  switch (type) {
    case actionTypes.QUEUE_SET_CUSTOM_EVENTS: {
      return {
        ...state,
        customEvents: payload
      };
    }
    case actionTypes.QUEUE_ADD_CUSTOM_EVENTS: {
      return {
        ...state,
        customEvents: state.customEvents.concat(payload)
      };
    }
    case actionTypes.QUEUE_CLEAR_CUSTOM_EVENTS: {
      return {
        ...state,
        customEvents: []
      };
    }
    default:
      return state;
  }
}
