import {store_items, filter_items, update_item} from './base'
import {flatten_array, property_getter} from 'common/utilities'

const initial_state = {
  shifts: {},
  events: {},
}

export default function shifts(state = initial_state, action) {
  switch (action.type) {
    case "store_shifts":
      return store_items(
        store_items(state, "events", flatten_array(action.shifts.map(property_getter("events")))),
        "shifts",
        action.shifts,
      )
    case "store_shift_events":
      return store_items(state, "events", action.events)
    case "replace_shift_events":
      return store_items(
        filter_items(
          update_item(state, "shifts", {id: action.shift_id, filled: true}),
          "events",
          ({calenderable_id}) => calenderable_id != action.shift_id
        ),
        "events",
        action.events
      )
    default:
      return state
  }
}
