import { createSlice, PayloadAction } from '@reduxjs/toolkit' import { LocationObject } from 'expo-location' import { Constants } from '@/constants/Constants' export type PlayerLocation = { id?: number playerId: number longitude: number latitude: number speed: number accuracy: number altitude: number altitudeAccuracy: number timestamp: string } interface LocationState { lastOwnLocation: LocationObject | null lastSentLocation: LocationObject | null queuedLocations: LocationObject[] lastPlayerLocations: PlayerLocation[] } const initialState: LocationState = { lastOwnLocation: null, lastSentLocation: null, queuedLocations: [], lastPlayerLocations: [] } export const locationSlice = createSlice({ name: 'location', initialState: initialState, reducers: { setLastLocation: (state, action: PayloadAction) => { const location: LocationObject = action.payload state.lastOwnLocation = location if (state.lastSentLocation === null || (location.timestamp - state.lastSentLocation.timestamp) >= Constants.MIN_DELAY_LOCATION_SENT * 1000) { state.lastSentLocation = location state.queuedLocations.push(location) } }, unqueueLocation: (state, action: PayloadAction) => { const sentLoc = action.payload state.queuedLocations = state.queuedLocations .filter(loc => new Date(loc.timestamp).getTime() !== sentLoc.timestamp && loc.coords.latitude !== sentLoc.coords.latitude && loc.coords.longitude !== sentLoc.coords.longitude) }, setLastPlayerLocations: (state, action: PayloadAction) => { state.lastPlayerLocations = action.payload }, setLastPlayerLocation: (state, action: PayloadAction) => { state.lastPlayerLocations = state.lastPlayerLocations.filter(playerLoc => playerLoc.playerId !== action.payload.playerId) state.lastPlayerLocations.push(action.payload) } }, }) export const { setLastLocation, unqueueLocation, setLastPlayerLocation, setLastPlayerLocations } = locationSlice.actions export default locationSlice.reducer