import { createReducer, on } from '@ngrx/store';
import { initialState, adapterInfoList } from './state';
import {
  infoSuccess,
  appendInfoList,
  info,
  infoFailure,
  recallInfoList,
  delInfoList,
  infoMoreSuccess
} from './actions';
import * as AuthenticationStore from '@app/store/account/authentication';
import { Info, EventType, EventJson } from '@ucap-webmessenger/protocol-event';
import { CONST } from '@ucap-webmessenger/core';

export const reducer = createReducer(
  initialState,
  on(info, (state, action) => {
    return {
      ...state,
      infoListProcessing: true
    };
  }),

  on(infoSuccess, (state, action) => {
    return {
      ...state,
      infoList: adapterInfoList.addAll(action.infoList, {
        ...state.infoList
      }),
      infoStatus: action.res,
      infoListProcessing: false,
      remainInfo:
        !!action.infoList &&
        action.infoList.length === CONST.EVENT_INFO_READ_COUNT
          ? true
          : false
    };
  }),
  on(infoMoreSuccess, (state, action) => {
    return {
      ...state,
      infoList: adapterInfoList.upsertMany(action.infoList, {
        ...state.infoList
      }),
      infoStatus: action.res,
      infoListProcessing: false,
      remainInfo:
        !!action.infoList &&
        action.infoList.length === CONST.EVENT_INFO_READ_COUNT
          ? true
          : false
    };
  }),

  on(infoFailure, (state, action) => {
    return {
      ...state,
      infoListProcessing: false
    };
  }),

  on(appendInfoList, (state, action) => {
    const eventinfo = action.info;

    const statusEventInfo: Info<EventJson> = {
      ...state.infoList.entities[eventinfo.seq],
      type: eventinfo.type,
      senderSeq: eventinfo.senderSeq,
      sendDate: eventinfo.sendDate,
      sentMessage: eventinfo.sentMessage,
      receiverCount: eventinfo.receiverCount
    };

    return {
      ...state,
      infoList: adapterInfoList.upsertOne(eventinfo, { ...state.infoList })
    };
  }),

  on(recallInfoList, (state, action) => {
    const eventSeq = action.eventSeq;

    const statusEventInfo: Info<EventJson> = {
      ...state.infoList.entities[eventSeq],
      type: EventType.RecalledMessage,
      sentMessage: '회수된 메시지'
    };

    return {
      ...state,
      infoList: adapterInfoList.updateOne(
        { id: eventSeq, changes: statusEventInfo },
        { ...state.infoList }
      )
    };
  }),

  on(delInfoList, (state, action) => {
    return {
      ...state,
      infoList: adapterInfoList.removeMany(action.eventSeqs, {
        ...state.infoList
      })
    };
  }),

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