import { createReducer, on } from '@ngrx/store';
import { initialState } from './state';
import {
  loginSuccess,
  increaseLoginFailCount,
  initialLoginFailCount,
  logoutInitialize,
  updateLoginRes,
  infoUserSuccess,
  updateStatusMessageSuccess
} from './actions';
import { UserInfoUpdateType } from '@ucap-webmessenger/protocol-info';
import { MessageIndexType } from '@ucap-webmessenger/protocol-status';

export const reducer = createReducer(
  initialState,
  on(loginSuccess, (state, action) => {
    return {
      ...state,
      loginRes: action.loginRes
    };
  }),

  on(updateLoginRes, (state, action) => {
    return {
      ...state,
      loginRes: action.loginRes
    };
  }),

  on(increaseLoginFailCount, (state, action) => {
    return {
      ...state,
      loginFailCount: state.loginFailCount + 1
    };
  }),

  on(initialLoginFailCount, (state, action) => {
    return {
      ...state,
      loginFailCount: 0
    };
  }),

  on(infoUserSuccess, (state, action) => {
    let loginRes = {
      ...state.loginRes
    };

    switch (action.res.type) {
      case UserInfoUpdateType.Image:
        loginRes = {
          ...loginRes
        };
        break;
      case UserInfoUpdateType.Intro:
        loginRes = {
          ...loginRes,
          userInfo: {
            ...loginRes.userInfo,
            intro: action.res.info
          }
        };
        break;
      case UserInfoUpdateType.TelephoneVisible:
        loginRes = {
          ...loginRes
        };
        break;
      default:
        break;
    }

    return {
      ...state,
      loginRes: {
        ...loginRes
      }
    };
  }),

  on(updateStatusMessageSuccess, (state, action) => {
    let loginRes = {
      ...state.loginRes
    };

    switch (action.res.index) {
      case MessageIndexType.First:
        loginRes = {
          ...loginRes,
          statusMessage1: action.res.statusMessage
        };
        break;
      case MessageIndexType.Second:
        loginRes = {
          ...loginRes,
          statusMessage2: action.res.statusMessage
        };
        break;
      case MessageIndexType.Third:
        loginRes = {
          ...loginRes,
          statusMessage3: action.res.statusMessage
        };
        break;
      default:
        break;
    }

    return {
      ...state,
      loginRes: {
        ...loginRes
      }
    };
  }),

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