import { createContext, createEffect, on, useContext } from "solid-js";
import { createStore } from "solid-js/store";
import { useWebsocket } from "./Websocket";
export const makeDataStreamContext = () => {
let intialized = false;
const [state, setState] = createStore({
favoriteStationIds: [15150280, 705556],
stationsToMonitor: [] as number[],
stations: [] as any[],
stationData: {} as any,
});
const [websocketState, _websocket]: any = useWebsocket();
createEffect(on(() => websocketState.socket, (socket: any) => {
if (intialized) return;
if (socket) {
intialized = true;
socket.on("station:monitor:data", (data: any) => {
console.log("DS: station:monitor:data", data);
});
socket.on("station:monitor:started", (data: any) => {
console.log("DS: station:monitor:started", data);
if (state.stations.filter((station) => station.id === data.station.id).length === 0) {
setState("stations", [...state.stations, { id: data.station.id, ident: data.station.ident, monitoring: true, messages: [] }]);
// if (stationIdSelected == data.stationId) setStore("stationSelected", data.station);
console.log(`DS: Browser ${data.browserId}: Started monitoring station ${data.station.id}`)
}
});
}
}));
return [state, {
addStationToMonitor: (stationId: number) => {
setState('stationsToMonitor', [...state.stationsToMonitor, stationId]);
websocketState.socket.emit("station:monitor:start", stationId);
},
removeStationToMonitor: (stationId: number) => {
setState('stationsToMonitor', state.stationsToMonitor.filter((id: number) => id !== stationId));
websocketState.socket.emit("station:monitor:stop", stationId);
}
}] as const;
}
export type DataStreamContextType = ReturnType<typeof makeDataStreamContext>;
export const DataStreamContext = createContext<DataStreamContextType>();
export const DataStreamProvider = (props: any) => {
const dataStream = makeDataStreamContext();
return (
<DataStreamContext.Provider value={dataStream}>
{props.children}
</DataStreamContext.Provider>
);
}
export const useDataStream = () => { return useContext(DataStreamContext); }