import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
import { getLatencyToUsers } from "../../helpers/rest"

const initialState = {
  status: 'idel',
  latencies: []
}


export const fetchUserLatencies = createAsyncThunk(
  'latency/fetchUserLatencies', 
  async (options, thunkAPI) => {
    const { currentUserId, participantIds } = options
    const response = await getLatencyToUsers(currentUserId, participantIds)
    return response.json()
  }
)

export const latencySlice = createSlice({
  name: 'latency',
  initialState,
  reducers: {
    add: (state, action) => {
      state.latencies.push(action.payload)
    }
  },
  extraReducers: (builder) => {
    builder
    .addCase(fetchUserLatencies.pending, (state, action) => {
      state.status = 'loading'
    })
    .addCase(fetchUserLatencies.fulfilled, (state, action) => {
      console.log("_DEBUG_ fetchUserLatencies", action.payload);
      const records = new Set([...state.latencies, ...action.payload]);
      const unique = [];
      records.map(x => unique.filter(a => a.user_id === x.user_id).length > 0 ? null : unique.push(x))
      state.latencies = unique
    })
    .addCase(fetchUserLatencies.rejected, (state, action) => {
      console.log("_DEBUG_ fail fetchUserLatencies", action.payload);
      state.status = 'failed'
    })
  }
})

export default latencySlice.reducer;