import { fetchServices, fetchServiceInfo } from 'modules/api_data/actions'

export const REQUEST_SERVICE_LIST_DATA = 'REQUEST_SERVICE_LIST_DATA'
export const requestServiceListData = (serviceType) => {
  return {
    type: REQUEST_SERVICE_LIST_DATA,
    serviceType: serviceType
  }
}

export const RECEIVE_SERVICE_LIST_DATA = 'RECEIEVE_SERVICE_LIST_DATA'
export const receiveServiceListData = (serviceType) => {
  return {
    type: RECEIVE_SERVICE_LIST_DATA,
    serviceType: serviceType
  }
}

export const RECEIVE_SERVICE_LIST_DATA_EXISTING = 'RECEIVE_SERVICE_LIST_DATA_EXISTING'
export const receiveServiceListDataExisting = (serviceType) => {
  return {
    type: RECEIVE_SERVICE_LIST_DATA_EXISTING,
    serviceType: serviceType
  }
}

export const RECEIVE_SERVICE_LIST_DATA_ERROR = 'RECEIVE_SERVICE_LIST_DATA_ERROR'
export const receiveServiceListDataError = (serviceType, error) => {
  return {
    type: RECEIVE_SERVICE_LIST_DATA_ERROR,
    serviceType: serviceType,
    error: error
  }
}

export function fetchServiceListData (serviceType) {
  return function (dispatch, getState) {
    dispatch(requestServiceListData(serviceType))
    Promise.all([
      dispatch(fetchServices())
    ])
    .then(
      () => {
        // Now fetch info objects for only the services we care about.
        const services = getState().api_data.services
        let tasks = []
        Object.keys(services).forEach((id, idx) => {
          const service = services[id]
          if (service.type === serviceType) {
            const task = dispatch(fetchServiceInfo(id, service.type))
            tasks.push(task)
          }
        })
        return Promise.all(tasks).then(() => { dispatch(receiveServiceListData(serviceType)) })
      }
    )
    .catch(
      (error) => {
        dispatch(receiveServiceListDataError(serviceType, error))
        return Promise.reject(error)
      }
    )
  }
}
