import { combineReducers } from 'redux'
import { UserAppData } from '../types'
import * as ActionTypes from './actionTypes'
import authReducer from './auth/reducer'
import { AuthDispatchTypes, AuthState } from './auth/types'
import userReducer from './user/reducer'
import relaysReducer from './relays/reducer'
import { RelaysDispatchTypes, RelaysState } from './relays/types'
import UserAppDataReducer from './userAppData/reducer'
import { UserAppDataDispatchTypes } from './userAppData/types'
import { UserDispatchTypes, UserState } from './user/types'
import { ServersDispatchTypes, FileServersState } from './servers/types.ts'
import serversReducer from './servers/reducer'

export interface State {
  auth: AuthState
  user: UserState
  relays: RelaysState
  servers: FileServersState
  userAppData?: UserAppData
}

type AppActions =
  | AuthDispatchTypes
  | UserDispatchTypes
  | RelaysDispatchTypes
  | ServersDispatchTypes
  | UserAppDataDispatchTypes

export const appReducer = combineReducers({
  auth: authReducer,
  user: userReducer,
  relays: relaysReducer,
  servers: serversReducer,
  userAppData: UserAppDataReducer
})

export default (
  state: ReturnType<typeof appReducer> | undefined,
  action: AppActions
) => {
  switch (action.type) {
    case ActionTypes.USER_LOGOUT:
      return appReducer(undefined, action)

    default:
      return appReducer(state, action)
  }
}
