import { fetchServices, fetchMetrics, fetchServiceInfo } from 'modules/api_data/actions'
import { fetchMetricsData } from 'modules/metrics_data/actions'
import { ServiceType } from 'modules/api_data/types'

export const REQUEST_SERVICE_INFO_DATA = 'REQUEST_SERVICE_INFO_DATA'
export const requestServiceInfoData = (serviceType) => {
  return {
    type: REQUEST_SERVICE_INFO_DATA,
    serviceType: serviceType
  }
}

export const RECEIVE_SERVICE_INFO_DATA = 'RECEIEVE_SERVICE_INFO_DATA'
export const receiveServiceInfoData = (serviceType) => {
  return {
    type: RECEIVE_SERVICE_INFO_DATA,
    serviceType: serviceType
  }
}

export const RECEIVE_SERVICE_INFO_DATA_EXISTING = 'RECEIVE_SERVICE_INFO_DATA_EXISTING'
export const receiveServiceInfoDataExisting = (serviceType) => {
  return {
    type: RECEIVE_SERVICE_INFO_DATA_EXISTING,
    serviceType: serviceType
  }
}

export const RECEIVE_SERVICE_INFO_DATA_ERROR = 'RECEIVE_SERVICE_INFO_DATA_ERROR'
export const receiveServiceInfoDataError = (serviceType, error) => {
  return {
    type: RECEIVE_SERVICE_INFO_DATA_ERROR,
    serviceType: serviceType,
    error: error
  }
}

export function fetchServiceInfoRoute (serviceId, serviceType, rangeType, bucketType, metricIds, reducerKeys) {
  return function (dispatch, getState) {
    dispatch(requestServiceInfoData(serviceType))
    Promise.all([
      dispatch(fetchServices())
    ])
    .then(
      () => {
        let tasks = []
        const services = getState().api_data.services
        tasks.push(dispatch(fetchServiceInfo(serviceId, serviceType)))
        tasks.push(dispatch(fetchMetrics()))
        if (serviceType !== ServiceType.PROJECT) {
          Object.keys(services).forEach((childId, idx) => {
            const child = services[childId]
            if (serviceType === ServiceType.ORG || child.parent === serviceId) {
              tasks.push(dispatch(fetchServiceInfo(childId, child.type)))
            }
          })
        }
        return Promise.all(tasks).then(() => {
          let subTasks = []
          reducerKeys.forEach((reducerKey, idx) => {
            if (idx === 0) {
              const allMetricIds = getState().api_data.metricIds
              subTasks.push(dispatch(fetchMetricsData([serviceId], allMetricIds, undefined, undefined, reducerKey)))
            } else {
              if (metricIds === undefined) {
                metricIds = getState().api_data.metricIds
              }
              subTasks.push(dispatch(fetchMetricsData([serviceId], metricIds, rangeType, bucketType, reducerKey)))
            }
          })
          Promise.all(subTasks).then(() => {
            dispatch(receiveServiceInfoData(serviceType))
          })
        })
      }
    )
    .catch(
      (error) => {
        dispatch(receiveServiceInfoDataError(serviceType, error))
        return Promise.reject(error)
      }
    )
  }
}
