import { REQUEST_METRICS, RECEIVE_METRICS, RECEIVE_BUCKETS } from '../actions'

export const metrics = (state = {}, action) => {
  switch (action.type) {
    case REQUEST_METRICS:
      return state
    case RECEIVE_METRICS:
      return Object.assign({}, state, action.metrics)

    /**
     * Special case to handle defining a 'type' for a metric.  The actual metric API call doesn't return any 'type'
     * information for a metric - that information is actually returned within the values that are in our 'buckets'.
     *
     * Since there are several places where we need to know the metric type in order to determine how we render stuff,
     * this will set the metric type once we receive a value for that metric.
     */
    case RECEIVE_BUCKETS:
      const metrics = Object.assign({}, state)
      action.metricIds.forEach((metricId) => {
        const metric = metrics[metricId]
        if (metric.type === undefined) {
          for (let bucket of action.buckets) {
            for (let serviceId of Object.keys(bucket.values)) {
              const serviceValues = bucket.values[serviceId]
              const value = serviceValues[metricId]
              if (value !== undefined) {
                metric.type = value.type
                metric.unit = value.unit
                break
              }
            }
            if (metric.type !== undefined && metric.unit !== undefined) {
              break
            }
          }
        }
      })
      return metrics
    default:
      return state
  }
}

export const metricIds = (state = [], action) => {
  switch (action.type) {
    case RECEIVE_METRICS:
      return Object.assign([], action.metricIds)
    default:
      return state
  }
}
