import { RECEIVE_BUCKETS } from '../actions'

export const ranges = (state = {}, action) => {
  switch (action.type) {
    case RECEIVE_BUCKETS:
      let newState = Object.assign({}, state)
      let buckets = action.buckets.map((bucket) => bucket.id)

      // Check to see if we already have this start time, if we don't then make a hash for it.
      if (newState[action.startTime] === undefined) {
        newState[action.startTime] = {}
      }

      // Check to see if we already have this endTime, if we don't then make a hash for it.
      if (newState[action.startTime][action.endTime] === undefined) {
        newState[action.startTime][action.endTime] = {}
      }

      // Check to see if we already have this bucketType.  If we don't then make a hash for it.
      if (newState[action.startTime][action.endTime][action.bucketType] === undefined) {
        newState[action.startTime][action.endTime][action.bucketType] = {
          buckets: [],
          cached: {}
        }
      }

      // Add our buckets to our list of buckets.
      let existingBuckets = newState[action.startTime][action.endTime][action.bucketType].buckets

      // It's possible we may have the same list of buckets again, so only add the unique buckets.
      buckets.forEach((bucketId) => {
        if (existingBuckets.indexOf(bucketId) === -1) {
          newState[action.startTime][action.endTime][action.bucketType].buckets.push(bucketId)
        }
      })

      // Add our map of cached values.
      let cached = newState[action.startTime][action.endTime][action.bucketType].cached
      action.serviceIds.forEach((serviceId) => {
        if (cached[serviceId] === undefined) {
          cached[serviceId] = {}
        }
        action.metricIds.forEach((metricId) => {
          if (cached[serviceId][metricId] === undefined) {
            cached[serviceId][metricId] = true
          }
        })
      })
      return newState
    default:
      return state
  }
}
