import { Event } from 'nostr-tools'
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 metadataReducer from './metadata/reducer'
import relaysReducer from './relays/reducer'
import { RelaysDispatchTypes, RelaysState } from './relays/types'
import UserAppDataReducer from './userAppData/reducer'
import userRobotImageReducer from './userRobotImage/reducer'
import { MetadataDispatchTypes } from './metadata/types'
import { UserAppDataDispatchTypes } from './userAppData/types'
import { UserRobotImageDispatchTypes } from './userRobotImage/types'

export interface State {
  auth: AuthState
  metadata?: Event
  userRobotImage?: string
  relays: RelaysState
  userAppData?: UserAppData
}

type AppActions =
  | AuthDispatchTypes
  | MetadataDispatchTypes
  | UserRobotImageDispatchTypes
  | RelaysDispatchTypes
  | UserAppDataDispatchTypes

export const appReducer = combineReducers({
  auth: authReducer,
  metadata: metadataReducer,
  userRobotImage: userRobotImageReducer,
  relays: relaysReducer,
  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)
  }
}
