import { HubConnectionState } from '@microsoft/signalr'

import { NotificationLogTypes } from './remote-notification.action.types'

const INITIAL_STATE = 
{
    inProgress: false,
    result: [],
    errorMessages: null,
    hubConnection: null,
    isConnected: false    
}

const remoteNotificationReducer = (currentState = INITIAL_STATE, action) => {
    switch(action.type){
        case NotificationLogTypes.NOTIFICATION_LOG_CONNECTION_START:
            return {
                ...currentState,
                inProgress: true,
                isConnected: false
            }
        case NotificationLogTypes.NOTIFICATION_LOG_CONNECTED:
            {
                const conn = action.payload
                return {
                    ...currentState,
                    inProgress: false,
                    hubConnection: conn,
                    isConnected: conn.state === HubConnectionState.Connected
                }
            }
            case NotificationLogTypes.NOTIFICATION_LOG_CONNECTION_FAILURE:
                return {
                    ...currentState,
                    inProgress: false,
                    errorMessages: action.payload,
                    hubConnection: null,
                    isConnected: false
                }
                case NotificationLogTypes.NOTIFICATION_LOG_RECEIVED_MESSAGE:
                    { 
                        const conn = currentState.hubConnection
                        return {
                            ...currentState,
                            result : action.payload ?? [],
                            isConnected: conn.state === HubConnectionState.Connected
                }
            }
        default: 
        return currentState
    }
}

export default remoteNotificationReducer