import Metric from '../objects/Metric'
import ApiUtil from 'utils/ApiUtil'

export const REQUEST_METRICS = 'REQUEST_METRICS'
export const RECEIVE_METRICS = 'RECEIVE_METRICS'
export const RECEIVE_METRICS_ERROR = 'RECEIVE_METRICS_ERROR'
export const RECEIVE_METRICS_EXISTING = 'RECEIVE_METRICS_EXISTING'

export function fetchMetrics () {
  return function (dispatch, getState) {
    dispatch(requestMetrics())
    if (getState().api_data.metricIds.length > 0) {
      dispatch(receiveMetricsExisting())
      return Promise.resolve()
    }
    return ApiUtil.getMetrics().then(
      json => dispatch(receiveMetrics(json))
    ).catch(
      (error) => {
        dispatch(receiveMetricsError(error))
        return Promise.reject(error)
      }
    )
  }
}

const requestMetrics = () => ({
  type: REQUEST_METRICS
})

function receiveMetrics (json) {
  let metrics = {}
  json.metrics.forEach((child) => {
    let metric = new Metric(child)
    metrics[metric.id] = metric
  })
  let metricIds = Object.keys(metrics)

  // // HACK: Add a custom metric called service health, for displaying health.
  // let healthMetric = new Metric(
  //   {
  //     metric_id: 'service_health',
  //     metric_name: 'Health',
  //     description: 'Placeholder metric for health'
  //   }
  // )
  // metrics[healthMetric.id] = healthMetric
  // metricIds.push(healthMetric.id)

  return {
    type: RECEIVE_METRICS,
    metrics: metrics,
    metricIds: metricIds.sort()
  }
}

function receiveMetricsError (error) {
  return {
    type: RECEIVE_METRICS_ERROR,
    error: error
  }
}

function receiveMetricsExisting () {
  return {
    type: RECEIVE_METRICS_EXISTING
  }
}
