import { REQUEST_BUCKETS, RECEIVE_BUCKETS } from '../actions'

export const buckets = (state = {}, action) => {
  switch (action.type) {
    case RECEIVE_BUCKETS:
      let bucketHash = {}
      // If we already have this bucket, then the new bucket needs to merge in our existing values.
      action.buckets.forEach((bucket) => {
        const existingBucket = state[bucket.id]
        if (existingBucket !== undefined) {
          bucket.mergeValues(existingBucket)
        }
        bucketHash[bucket.id] = bucket
      })
      return Object.assign({}, state, bucketHash)
    default:
      return state
  }
}

export const fetchedBuckets = (state = {}, action) => {
  switch (action.type) {
    case REQUEST_BUCKETS:
      return {}
    case RECEIVE_BUCKETS:
      let newState = Object.assign({}, state)
      action.serviceIds.forEach((serviceId) => {
        if (newState[serviceId] === undefined) {
          newState[serviceId] = {}
        }
        action.metricIds.forEach((metricId) => {
          newState[serviceId][metricId] = true
        })
      })
      return newState
    default:
      return state
  }
}
