import MessagingActionTypes from "./messaging.types";

const INITIAL_STATE = {
  visible: false,
  conversations: [
    { phone: "6049992002", open: false },
    { phone: "6049992991", open: false }
  ]
};

const messagingReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case MessagingActionTypes.TOGGLE_CHAT_VISIBLE:
      return {
        ...state,
        visible: !state.visible
      };
    case MessagingActionTypes.SET_CHAT_VISIBLE:
      return {
        ...state,
        visible: true
      };
    case MessagingActionTypes.OPEN_CONVERSATION:
      if (state.conversations.find(c => c.phone === action.payload))
        return {
          ...state,
          conversations: state.conversations.map(c =>
            c.phone === action.payload ? { ...c, open: true } : c
          )
        };
      else
        return {
          ...state,
          conversations: [
            ...state.conversations,
            { phone: action.payload, open: true }
          ]
        };
    case MessagingActionTypes.CLOSE_CONVERSATION:
      return {
        ...state,
        conversations: state.conversations.filter(
          c => c.phone !== action.payload
        )
      };
    case MessagingActionTypes.TOGGLE_CONVERSATION_VISIBLE:
      return {
        ...state,
        conversations: state.conversations.map(c =>
          c.phone === action.payload ? { ...c, open: !c.open } : c
        )
      };
    default:
      return state;
  }
};

export default messagingReducer;
