import {createSlice} from '@reduxjs/toolkit';
import type {PayloadAction} from '@reduxjs/toolkit';

import {appStatus, non_save_vars} from './appNonSaveVar';
import {User} from '@caj/user/types';
import {UserId} from './types';
import {chatEntity, chatId} from '@caj/components/chat/types';

export const appNonSaveVariablesSlice = createSlice({
  name: 'non_save_vars',
  initialState: non_save_vars,
  reducers: {
    setAppStatus: (state, action: PayloadAction<appStatus>) => {
      state.appStatus = action.payload;
    },
    setCachedUser: (state, action: PayloadAction<User>) => {
      state.cachedUsers[action.payload.UserId] = action.payload;
    },
    removeCachedUser: (state, action: PayloadAction<UserId>) => {
      delete state.cachedUsers[action.payload];
    },
    setSelectedChat: (state, action: PayloadAction<chatId>) => {
      state.selectedChat = action.payload;
    },
    setChatEntity: (state, action: PayloadAction<chatEntity>) => {
      const chatId = action.payload.id;

      state.chats[chatId] = action.payload;

      if (state.chatActivity.includes(chatId) === false)
        state.chatActivity.unshift(chatId);
    },
    changeChatEntity: (state, action: PayloadAction<chatEntity>) => {
      const chatId = action.payload.id;

      state.chats[chatId] = action.payload;

      if (state.chatActivity.includes(chatId) === false)
        state.chatActivity.unshift(chatId);
      state.chatActivity.sort(function (x, y) {
        return x == chatId ? -1 : y == chatId ? 1 : 0;
      });
    },
    removeChatEntity: (state, action: PayloadAction<chatId>) => {
      delete state.chats[action.payload];

      state.chatActivity = state.chatActivity.filter(function (ele) {
        return ele !== action.payload;
      });
    },
  },
});

// Action creators are generated for each case reducer function
const {actions} = appNonSaveVariablesSlice;
export const appNonSaveVarActions = actions;

export default appNonSaveVariablesSlice.reducer;
