import { fetchServices, fetchMetrics } from 'modules/api_data/actions'
import { fetchMetricsData } from 'modules/metrics_data/actions'
import { REDUCER_KEY } from '../reducers/metrics_table'

export const REQUEST_METRICS_ROUTE = 'REQUEST_METRICS_ROUTE'
export const requestMetricsRoute = () => {
  return {
    type: REQUEST_METRICS_ROUTE
  }
}

export const RECEIVE_METRICS_ROUTE = 'RECEIVE_METRICS_ROUTE'
export const receiveMetricsRoute = () => {
  return {
    type: RECEIVE_METRICS_ROUTE
  }
}

export const RECEIVE_METRICS_ROUTE_EXISTING = 'RECEIVE_METRICS_ROUTE_EXISTING'
export const receiveMetricsRouteExisting = () => {
  return {
    type: RECEIVE_METRICS_ROUTE_EXISTING
  }
}

export const RECEIVE_METRICS_ROUTE_ERROR = 'RECEIVE_METRICS_ROUTE_ERROR'
export const receiveMetricsRouteError = (error) => {
  return {
    type: RECEIVE_METRICS_ROUTE_ERROR,
    error: error
  }
}

export function fetchMetricsRoute (serviceIds, metricIds, rangeType, bucketType) {
  return function (dispatch, getState) {
    dispatch(requestMetricsRoute())
    Promise.all([
      dispatch(fetchServices()),
      dispatch(fetchMetrics())
    ])
    .then(() => {
      if (metricIds === undefined) {
        metricIds = getState().api_data.metricIds
      }
      if (serviceIds === undefined) {
        serviceIds = getState().api_data.orgIds
      }
      return Promise.all([dispatch(fetchMetricsData(serviceIds, metricIds, rangeType, bucketType, REDUCER_KEY))])
    })
    .then(() => {
      return dispatch(receiveMetricsRoute())
    })
    .catch(
      (error) => {
        dispatch(receiveMetricsRouteError(error))
        return Promise.reject(error)
      }
    )
  }
}
