export const initialState = {
  amount: 30,
  male: true,
  simulate: false,
  items: [],
}

const ENTRY_BUFFER = 10

function dynamicSort(property) {
  return function(a, b) {
      return (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0
  }
}

function reducer(state, action) {
  switch (action.type) {
    case "UPDATE_FILTER":
      state = { ...state, ...action.payload, }
      if (!action.payload.simulate) {
        state.items = []
      }
      break
    case "GENERATE_ITEMS": {
        const items = action.payload.wrestlers
          .sort(() => .5 - Math.random())
          .filter(item => item.male === state.male).slice(0, state.amount)
          .map((model, entry) => ({
            model,
            entry,
            elimination: null,
          }))
          .sort(dynamicSort("entry"))

        state = { ...state, items, }
      }
      break
    case "ELIMINATE_ITEM": {
      const eliminationNumber = Math.max(...state.items.map(o => o.elimination), 0) + 1
      const remainers = state.items.filter(item => !item.elimination && item.entry < eliminationNumber + ENTRY_BUFFER)

      if (remainers.length > 0 && state.amount !== eliminationNumber) {
        const randomPick = Math.floor(Math.random() * remainers.length)
        const eliminatedId = remainers[randomPick].model.id
        const overallIndex = state.items.findIndex(item => item.model.id === eliminatedId)

        state.items[overallIndex].elimination = eliminationNumber
      } else {
        state.simulate = false
      }
    } break
    default:
      break
  }

  return state
}

export default reducer
