import {createSlice} from '@reduxjs/toolkit';
import type {PayloadAction} from '@reduxjs/toolkit';
import {appStatus, non_save_vars} from './appNonSaveVar';
import {ThemeTokensType} from '@configs/colors';

import {chatEntity, roomId} from '@configs/chat/types';
import {User} from '@user/types';
import {AccountName} from './types';
import {PA_Point} from '@components/map/cluster/getData';

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

      state.chats[roomId] = action.payload;

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

      state.chats[roomId] = action.payload;

      if (state.chatActivity.includes(roomId) === false)
        state.chatActivity.unshift(roomId);

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

      state.chatActivity = state.chatActivity.filter(function (ele) {
        return ele !== action.payload;
      });
    },
    setMapMarkers: (state, action: PayloadAction<PA_Point[]>) => {
      state.eventMapMarkers = action.payload;
    },
  },
});

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

export default appNonSaveVariablesSlice.reducer;
