File size: 1,545 Bytes
08c0cf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import React, { createContext, useContext, useState, useEffect, useMemo } from 'react';
import { config } from '../config';
import useWebSocket from '../hooks/useWebSocket';
const AppContext = createContext();

export const AppProvider = ({ children }) => {
    const [globalMaxSteps, setGlobalMaxSteps] = useState(30);
    const [simulationSeconds, setSimulationSeconds] = useState(0);
    const { gameState, isConnected, sendCommand } = useWebSocket(config.WS_URL);

    useEffect(() => {
        const status = gameState?.status;
        if (status === 'STANDBY' || status === 'COMPLETED') {
            setSimulationSeconds(0);
            return;
        }
        if (status === 'PAUSED') {
            return;
        }
        const interval = setInterval(() => {
            setSimulationSeconds(s => s + 1);
        }, 1000);
        return () => clearInterval(interval);
    }, [gameState?.status]);

    const value = useMemo(() => ({
        sessionData: gameState,
        isConnected,
        sendCommand,
        globalMaxSteps,
        setGlobalMaxSteps,
        simulationSeconds
    }), [gameState, isConnected, sendCommand, globalMaxSteps, simulationSeconds]);

    return (
        <AppContext.Provider value={value}>

            {children}

        </AppContext.Provider>
    );
};

export const useApp = () => {
    const context = useContext(AppContext);
    if (!context) {
        throw new Error('useApp must be used within an AppProvider');
    }
    return context;
};