import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  activeUsers: localStorage.getItem("activeOnes")
    ? JSON.parse(localStorage.getItem("activeOnes"))
    : [],
  connection: ''
};

const statusSlice = createSlice({
  name: "status",
  initialState,
  reducers: {
    // when an user logs in signalR delivers the list of all active users to him, so we
    // just set it into our state menagement
    setActiveUsers: (state, action) => {
      state.activeUsers = action.payload;
      localStorage.setItem("activeOnes", JSON.stringify(action.payload));
    },
    // when another user logs in, signalR hub sends his id to all other
    // clients so we just add his id to the array of active users ids
    addToActiveUsers: (state, action) => {
      state.activeUsers.push(action.payload);
      localStorage.setItem(
        "activeOnes",
        JSON.stringify([...state.activeUsers, action.payload])
      );
    },
    // when another user logs out, signalR hub sends his id to all other clients
    // so we just filter the array of active user ids so that we take the id of the
    // user who left out
    removeFromActiveUsers: (state, action) => {
      state.activeUsers = state.activeUsers.filter((n) => n !== action.payload);
      localStorage.setItem(
        "activeOnes",
        JSON.stringify([...state.activeUsers, action.payload])
      );
    },
    // maybe needed later
    resetActiveUsers: (state, action) => {
      state.activeUsers = [];
      localStorage.removeItem("activeOnes");
    },
    //  connection may be needed later
    setStatusConn: (state, action) => {
      state.connection = action.payload;
    }
  },
});

export const statusActions = statusSlice.actions;
export const statusReducers = statusSlice.reducer;
