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

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

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(statusSuccess, (state, action) => {
    const statusBulkInfoState: StatusBulkInfo = {
      ...state.statusBulkInfo.entities[action.res.SENDER_SEQ],
      pcStatus: action.res.statusType,
      statusMessage: action.res.statusMessage
    };

    return {
      ...state,
      statusBulkInfo: adapterStatusBulkInfo.updateOne(
        { id: action.res.SENDER_SEQ, changes: statusBulkInfoState },
        { ...state.statusBulkInfo }
      ),
      myStatus: {
        ...state.myStatus,
        pcStatus: action.res.statusType,
        statusMessage: action.res.statusMessage
      }
    } as State;
  }),

  on(AuthenticationStore.loginSuccess, (state, action) => {
    return {
      ...state,
      myStatus: {
        userSeq: action.loginRes.userSeq,
        pcStatus: StatusCode.OnLine,
        phoneStatus: StatusCode.Offline,
        mobileStatus: StatusCode.Offline,
        conferenceStatus: StatusCode.Offline,
        statusMessage: '',
        mobileConferenceStatus: StatusCode.Offline,
        imessengerStatus: StatusCode.Offline
      }
    };
  }),

  on(changeMyIdleCheckTime, (state, action) => {
    return {
      ...state,
      myIdleCheckTime: action.checkTime
    } as State;
  }),

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