summaryrefslogtreecommitdiff
path: root/lib/device.tsx
blob: e0ec60099c50bb029bd3b5be50f44cabb81febfa (plain)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import {
  createContext,
  ReactNode,
  useCallback,
  useContext,
  useEffect,
  useState,
} from "react";
import { apiClient, getDevices } from "../api";
import { Device } from "../api/types";
import { useAuth } from "./auth";

type DeviceContextType = {
  devices: Device[];
  selectedDevice: Device | null;
  isLoading: boolean;
  selectDevice: (device: Device) => Promise<void>;
  refreshDevices: () => Promise<void>;
};

const DeviceContext = createContext<DeviceContextType | null>(null);

export function DeviceProvider({ children }: { children: ReactNode }) {
  const [devices, setDevices] = useState<Device[]>([]);
  const [selectedDevice, setSelectedDevice] = useState<Device | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const { isAuthenticated } = useAuth();

  const refreshDevices = useCallback(async () => {
    if (!isAuthenticated) {
      setIsLoading(false);
      return;
    }

    setIsLoading(true);
    try {
      const fetchedDevices = await getDevices();
      setDevices(fetchedDevices);

      // If no device is selected, try to restore from storage or select first device
      if (!selectedDevice && fetchedDevices.length > 0) {
        const savedDeviceId = apiClient.getSelectedDeviceId();
        const savedDevice = fetchedDevices.find((d) => d.id === savedDeviceId);

        if (savedDevice) {
          setSelectedDevice(savedDevice);
        } else {
          // Select first device by default
          setSelectedDevice(fetchedDevices[0]!);
          await apiClient.setSelectedDevice(fetchedDevices[0]!.id);
        }
      }
    } catch (e) {
      console.error("Failed to refresh devices", e);
    } finally {
      setIsLoading(false);
    }
  }, [selectedDevice, isAuthenticated]);

  useEffect(() => {
    refreshDevices();
  }, [refreshDevices]);

  const selectDevice = useCallback(async (device: Device) => {
    setSelectedDevice(device);
    await apiClient.setSelectedDevice(device.id);
  }, []);

  return (
    <DeviceContext.Provider
      value={{
        devices,
        selectedDevice,
        isLoading,
        selectDevice,
        refreshDevices,
      }}
    >
      {children}
    </DeviceContext.Provider>
  );
}

export function useDevice() {
  const context = useContext(DeviceContext);
  if (!context) {
    throw new Error("useDevice must be used within a DeviceProvider");
  }
  return context;
}