import { createReducer, on } from '@ngrx/store';
import { initialState, adapterUserInfo, adapterUserInfoShort } from './state';
import {
  infoSuccess,
  updateSuccess,
  updateRoomUserLastReadSeq,
  updateTimeRoomIntervalSuccess
} from './actions';

import * as AuthenticationStore from '@app/store/account/authentication';
import * as ChatStore from '@app/store/messenger/chat';
import { UserInfo } from '@ucap-webmessenger/protocol-room';

export const reducer = createReducer(
  initialState,
  on(infoSuccess, (state, action) => {
    return {
      ...state,
      roomInfo: action.roomInfo,
      userInfoList: adapterUserInfo.addAll(action.userInfoList, {
        ...state.userInfoList
      }),
      userInfoShortList: adapterUserInfoShort.addAll(action.userInfoShortList, {
        ...state.userInfoShortList
      })
    };
  }),

  on(updateSuccess, (state, action) => {
    return {
      ...state,
      roomInfo: {
        ...state.roomInfo,
        roomName: action.res.roomName,
        receiveAlarm: action.res.receiveAlarm
      }
    };
  }),

  on(updateTimeRoomIntervalSuccess, (state, action) => {
    return {
      ...state,
      roomInfo: {
        ...state.roomInfo,
        timeRoomInterval: action.res.timerInterval
      }
    };
  }),

  on(updateRoomUserLastReadSeq, (state, action) => {
    const userSeq = action.SENDER_SEQ;

    const userInfo: UserInfo = {
      ...state.userInfoList.entities[userSeq],
      lastReadEventSeq: action.lastReadSeq
    };

    return {
      ...state,
      userInfoList: adapterUserInfo.updateOne(
        { id: userSeq, changes: userInfo },
        { ...state.userInfoList }
      )
    };
  }),

  on(ChatStore.clearSelectedRoom, (state, action) => {
    return {
      ...initialState
    };
  }),

  on(AuthenticationStore.logoutInitialize, (state, action) => {
    return {
      ...initialState
    };
  })
);
