import {createReducer} from '@reduxjs/toolkit';
import {
  CLEAR_ERROR,
  CLEAR_INFO,
  SET_ERROR_INFO,
  SET_INFO
} from '../actions/error_actions';

export const errorReducer = createReducer({
  DisplayError: false,
  DisplayInfo: false,
  ErrorCritical: false,
  ErrorStack: [],
  InfoStack: [],
}, {
  [CLEAR_ERROR]: state => {
    const errorStack = (state.ErrorStack.length > 0) ? state.ErrorStack.slice(1) : [];
    return {
      ...state,
      DisplayError: (errorStack.length > 0),
      ErrorStack: errorStack,
    }
  },
  [CLEAR_INFO]: state => {
    const infoStack = (state.InfoStack.length > 0) ? state.InfoStack.slice(1) : [];
    return {
      ...state,
      DisplayInfo: (infoStack.length > 0),
      InfoStack: infoStack,
    }
  },
  [SET_ERROR_INFO]: (state, action) => {
    const errorStack = [action.payload.msg, ...state.ErrorStack];
    return {
      ...state,
      DisplayError: true,
      ErrorCritical: state.ErrorCritical || action.payload.critical,
      ErrorStack: errorStack,
    }
  },
  [SET_INFO]: (state, action) => {
    const infoStack = [{
      title: action.payload.title,
      message: action.payload.msg
    }, ...state.InfoStack];
    return {
      ...state,
      DisplayInfo: true,
      InfoStack: infoStack,
    }
  }
});
