import { createReducer, on } from '@ngrx/store';
import { initialState, State, adapterStatusBulkInfo } from './state';
import { bulkInfoSuccess, statusNotification } from './actions';

import * as AuthenticationStore from '@app/store/account/authentication';
import { StatusBulkInfo } from '@ucap-webmessenger/protocol-status';

export const reducer = createReducer(
  initialState,
  on(bulkInfoSuccess, (state, action) => {
    return {
      ...state,
      statusBulkInfo: adapterStatusBulkInfo.upsertMany(
        action.statusBulkInfoList,
        {
          ...state.statusBulkInfo
        }
      )
    } as State;
  }),

  on(statusNotification, (state, action) => {
    const noti = action.noti;

    const statusBulkInfoState: StatusBulkInfo = {
      ...state.statusBulkInfo.entities[noti.userSeq],
      conferenceStatus: noti.conferenceStatus,
      imessengerStatus: noti.imessengerStatus,
      mobileConferenceStatus: noti.mobileConferenceStatus,
      mobileStatus: noti.mobileStatus,
      pcStatus: noti.pcStatus,
      phoneStatus: noti.phoneStatus,
      statusMessage: noti.statusMessage
    };

    return {
      ...state,
      statusBulkInfo: adapterStatusBulkInfo.updateOne(
        { id: noti.userSeq, changes: statusBulkInfoState },
        { ...state.statusBulkInfo }
      )
    };
  }),

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