import { ActionType, AuthActions, ChatActions } from '../actions';
import { MapOfChatRooms } from '../models';

const INITIAL_STATE: MapOfChatRooms = {};

export function chatReducer(state = INITIAL_STATE, action: ActionType): MapOfChatRooms {
  switch (action.type) {
    case ChatActions.ActionKey.CONVERSATION_ADDDED: {
      return {
        ...state,
        [action.conversation.id]: {
          conversationId: action.conversation.id,
          messages: [],
        },
      };
    }
    case ChatActions.ActionKey.NEW_MESSAGE_RECEIVED: {
      const conversationId = action.conversationId;
      const chatRoom = state[conversationId];
      return {
        ...state,
        [conversationId]: {
          ...chatRoom,
          messages: [
            ...(chatRoom && chatRoom.messages || []),
            action.message,
          ],
        },
      };
    }
    case AuthActions.ActionKey.LOGOUT_REQUESTED: {
      return INITIAL_STATE;
    }
    default:
      return state;
  }
}
