import { combineReducers } from 'redux'
import { ServiceType } from 'modules/api_data/types'
import { LOCATION_CHANGE } from 'store/location'
import {
  REQUEST_SERVICE_INFO_DATA,
  RECEIVE_SERVICE_INFO_DATA,
  RECEIVE_SERVICE_INFO_DATA_ERROR
} from 'routes/Services/actions'

const loading = (state = true, action) => {
  switch (action.type) {
    case LOCATION_CHANGE:
      if (action.payload.pathname.startsWith('/teams/') && action.payload.action === 'PUSH') {
        return true
      }
      return state
    case REQUEST_SERVICE_INFO_DATA:
      if (action.serviceType === ServiceType.TEAM) {
        return true
      }
      return state
    case RECEIVE_SERVICE_INFO_DATA:
    case RECEIVE_SERVICE_INFO_DATA_ERROR:
      if (action.serviceType === ServiceType.TEAM) {
        return false
      }
      return state
    default:
      return state
  }
}

const error = (state = null, action) => {
  switch (action.type) {
    case LOCATION_CHANGE:
      if (action.payload.pathname.startsWith('/teams/') && action.payload.action === 'PUSH') {
        return null
      }
      return state
    case REQUEST_SERVICE_INFO_DATA:
      if (action.serviceType === ServiceType.TEAM) {
        return null
      }
      return state
    case RECEIVE_SERVICE_INFO_DATA_ERROR:
      if (action.serviceType === ServiceType.TEAM) {
        return action.error.toString()
      }
      return state
    default:
      return state
  }
}

export default combineReducers({
  loading,
  error
})
