All files / web/src/components/vision AbacusVisionContext.tsx

0% Statements 0/401
0% Branches 0/1
0% Functions 0/1
0% Lines 0/401

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
'use client'

import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'
import { useAbacusVision } from '@/hooks/useAbacusVision'
import { useRemoteCameraDesktop, type FrameMode } from '@/hooks/useRemoteCameraDesktop'
import type {
  CalibrationGrid,
  CalibrationMode,
  QuadCorners,
  UseAbacusVisionReturn,
} from '@/types/vision'

// ============================================================================
// Types
// ============================================================================

export type CameraSource = 'local' | 'phone'

export interface RemoteCameraState {
  /** Current session ID */
  sessionId: string | null
  /** Whether phone is connected to the session */
  isPhoneConnected: boolean
  /** Whether actively trying to reconnect */
  isReconnecting: boolean
  /** Latest frame from phone */
  latestFrame: {
    imageData: string
    timestamp: number
    mode?: FrameMode
    videoDimensions?: { width: number; height: number }
    detectedCorners?: QuadCorners | null
  } | null
  /** Current frame mode (raw for calibration, cropped for detection) */
  frameMode: FrameMode
  /** Video dimensions from phone (only in raw mode) */
  videoDimensions: { width: number; height: number } | null
  /** Corners detected by phone's marker detection */
  phoneDetectedCorners: QuadCorners | null
  /** Phone torch state */
  isTorchOn: boolean
  isTorchAvailable: boolean
  /** Frame rate */
  frameRate: number
  /** Connection error */
  error: string | null
}

export interface RemoteCameraActions {
  /** Subscribe to a session */
  subscribe: (sessionId: string) => void
  /** Unsubscribe from current session */
  unsubscribe: () => void
  /** Set phone frame mode */
  setPhoneFrameMode: (mode: FrameMode) => void
  /** Send calibration corners to phone */
  sendCalibration: (corners: QuadCorners, columnCount: number, preview?: boolean) => void
  /** Clear calibration on phone */
  clearCalibration: () => void
  /** Toggle phone torch */
  setRemoteTorch: (on: boolean) => void
  /** Get persisted session ID */
  getPersistedSessionId: () => string | null
  /** Clear session and disconnect */
  clearSession: () => void
}

export interface CalibrationState {
  /** Whether currently in calibration mode */
  isCalibrating: boolean
  /** Current calibration grid */
  calibration: CalibrationGrid | null
  /** Whether calibration is complete */
  isCalibrated: boolean
  /** Current corners being edited (during calibration) */
  editingCorners: QuadCorners | null
  /** Current column dividers being edited */
  editingDividers: number[] | null
}

export interface CalibrationActions {
  /** Start calibration mode */
  startCalibration: () => void
  /** Finish calibration with the given grid */
  finishCalibration: (grid: CalibrationGrid) => void
  /** Cancel calibration without saving */
  cancelCalibration: () => void
  /** Update corners during calibration (for live preview) */
  setEditingCorners: (corners: QuadCorners) => void
  /** Update dividers during calibration */
  setEditingDividers: (dividers: number[]) => void
  /** Rotate corners 90 degrees */
  rotateCorners: (direction: 'left' | 'right') => void
  /** Reset to default calibration */
  resetCalibration: () => void
}

export interface AbacusVisionContextValue {
  // Camera source
  cameraSource: CameraSource
  setCameraSource: (source: CameraSource) => void

  // Column count
  columnCount: number
  setColumnCount: (count: number) => void

  // Local camera (full useAbacusVision return)
  localCamera: UseAbacusVisionReturn

  // Remote camera state and actions
  remoteCamera: RemoteCameraState & RemoteCameraActions

  // Remote calibration (separate from local)
  remoteCalibration: CalibrationState & CalibrationActions

  // Detection results (from whichever source is active)
  detection: {
    value: number | null
    confidence: number
    isStable: boolean
    consecutiveFrames: number
  }

  // Callbacks
  onValueDetected?: (value: number) => void
  onConfigurationChange?: (config: {
    columnCount?: number
    cameraSource?: CameraSource
    remoteCameraSessionId?: string | null
  }) => void
}

// ============================================================================
// Context
// ============================================================================

const AbacusVisionContext = createContext<AbacusVisionContextValue | null>(null)

// ============================================================================
// Hook
// ============================================================================

export function useAbacusVisionContext(): AbacusVisionContextValue {
  const context = useContext(AbacusVisionContext)
  if (!context) {
    throw new Error('useAbacusVisionContext must be used within AbacusVisionProvider')
  }
  return context
}

// ============================================================================
// Provider Props
// ============================================================================

export interface AbacusVisionProviderProps {
  children: ReactNode
  /** Initial column count */
  initialColumnCount?: number
  /** Initial camera source */
  initialCameraSource?: CameraSource
  /** Called when a stable value is detected */
  onValueDetected?: (value: number) => void
  /** Called when configuration changes */
  onConfigurationChange?: (config: {
    columnCount?: number
    cameraSource?: CameraSource
    remoteCameraSessionId?: string | null
  }) => void
}

// ============================================================================
// Provider
// ============================================================================

export function AbacusVisionProvider({
  children,
  initialColumnCount = 5,
  initialCameraSource = 'local',
  onValueDetected,
  onConfigurationChange,
}: AbacusVisionProviderProps) {
  // -------------------------------------------------------------------------
  // Core State
  // -------------------------------------------------------------------------
  const [cameraSource, setCameraSourceState] = useState<CameraSource>(initialCameraSource)
  const [columnCount, setColumnCountState] = useState(initialColumnCount)

  // -------------------------------------------------------------------------
  // Local Camera (via useAbacusVision)
  // -------------------------------------------------------------------------
  const localCamera = useAbacusVision({
    columnCount,
    onValueDetected: cameraSource === 'local' ? onValueDetected : undefined,
  })

  // -------------------------------------------------------------------------
  // Remote Camera (via useRemoteCameraDesktop)
  // -------------------------------------------------------------------------
  const remoteDesktop = useRemoteCameraDesktop()

  // Remote calibration state (managed separately from local)
  const [remoteIsCalibrating, setRemoteIsCalibrating] = useState(false)
  const [remoteCalibrationGrid, setRemoteCalibrationGrid] = useState<CalibrationGrid | null>(null)
  const [remoteEditingCorners, setRemoteEditingCorners] = useState<QuadCorners | null>(null)
  const [remoteEditingDividers, setRemoteEditingDividers] = useState<number[] | null>(null)

  // -------------------------------------------------------------------------
  // Camera Source Setter (with callback)
  // -------------------------------------------------------------------------
  const setCameraSource = useCallback(
    (source: CameraSource) => {
      setCameraSourceState(source)
      onConfigurationChange?.({ cameraSource: source })
    },
    [onConfigurationChange]
  )

  // -------------------------------------------------------------------------
  // Column Count Setter (with callback)
  // -------------------------------------------------------------------------
  const setColumnCount = useCallback(
    (count: number) => {
      setColumnCountState(count)
      onConfigurationChange?.({ columnCount: count })
    },
    [onConfigurationChange]
  )

  // -------------------------------------------------------------------------
  // Remote Calibration Actions
  // -------------------------------------------------------------------------
  const startRemoteCalibration = useCallback(() => {
    setRemoteIsCalibrating(true)
    // Tell phone to send raw (uncropped) frames for calibration
    remoteDesktop.setPhoneFrameMode('raw')
  }, [remoteDesktop])

  const finishRemoteCalibration = useCallback(
    (grid: CalibrationGrid) => {
      setRemoteCalibrationGrid(grid)
      setRemoteIsCalibrating(false)
      setRemoteEditingCorners(null)
      setRemoteEditingDividers(null)
      // Send calibration to phone - phone will auto-switch to cropped mode
      if (grid.corners) {
        remoteDesktop.sendCalibration(grid.corners, columnCount)
      }
    },
    [remoteDesktop, columnCount]
  )

  const cancelRemoteCalibration = useCallback(() => {
    setRemoteIsCalibrating(false)
    setRemoteEditingCorners(null)
    setRemoteEditingDividers(null)
    // If we had previous calibration, keep using it
    // Otherwise phone stays in raw mode
  }, [])

  const rotateRemoteCorners = useCallback((direction: 'left' | 'right') => {
    setRemoteEditingCorners((prev) => {
      if (!prev) return prev
      if (direction === 'right') {
        // Rotate 90 clockwise: TL->TR, TR->BR, BR->BL, BL->TL
        return {
          topLeft: prev.bottomLeft,
          topRight: prev.topLeft,
          bottomRight: prev.topRight,
          bottomLeft: prev.bottomRight,
        }
      } else {
        // Rotate 90 counter-clockwise
        return {
          topLeft: prev.topRight,
          topRight: prev.bottomRight,
          bottomRight: prev.bottomLeft,
          bottomLeft: prev.topLeft,
        }
      }
    })
  }, [])

  const resetRemoteCalibration = useCallback(() => {
    setRemoteCalibrationGrid(null)
    setRemoteEditingCorners(null)
    setRemoteEditingDividers(null)
    remoteDesktop.clearCalibration()
  }, [remoteDesktop])

  // -------------------------------------------------------------------------
  // Remote Camera State Object
  // -------------------------------------------------------------------------
  const remoteCameraState: RemoteCameraState & RemoteCameraActions = useMemo(
    () => ({
      // State
      sessionId: remoteDesktop.currentSessionId,
      isPhoneConnected: remoteDesktop.isPhoneConnected,
      isReconnecting: remoteDesktop.isReconnecting,
      latestFrame: remoteDesktop.latestFrame,
      frameMode: remoteDesktop.frameMode,
      videoDimensions: remoteDesktop.videoDimensions,
      phoneDetectedCorners: remoteDesktop.phoneDetectedCorners,
      isTorchOn: remoteDesktop.isTorchOn,
      isTorchAvailable: remoteDesktop.isTorchAvailable,
      frameRate: remoteDesktop.frameRate,
      error: remoteDesktop.error,
      // Actions
      subscribe: remoteDesktop.subscribe,
      unsubscribe: remoteDesktop.unsubscribe,
      setPhoneFrameMode: remoteDesktop.setPhoneFrameMode,
      sendCalibration: remoteDesktop.sendCalibration,
      clearCalibration: remoteDesktop.clearCalibration,
      setRemoteTorch: remoteDesktop.setRemoteTorch,
      getPersistedSessionId: remoteDesktop.getPersistedSessionId,
      clearSession: remoteDesktop.clearSession,
    }),
    [remoteDesktop]
  )

  // -------------------------------------------------------------------------
  // Remote Calibration State Object
  // -------------------------------------------------------------------------
  const remoteCalibrationState: CalibrationState & CalibrationActions = useMemo(
    () => ({
      // State
      isCalibrating: remoteIsCalibrating,
      calibration: remoteCalibrationGrid,
      isCalibrated: remoteCalibrationGrid !== null,
      editingCorners: remoteEditingCorners,
      editingDividers: remoteEditingDividers,
      // Actions
      startCalibration: startRemoteCalibration,
      finishCalibration: finishRemoteCalibration,
      cancelCalibration: cancelRemoteCalibration,
      setEditingCorners: setRemoteEditingCorners,
      setEditingDividers: setRemoteEditingDividers,
      rotateCorners: rotateRemoteCorners,
      resetCalibration: resetRemoteCalibration,
    }),
    [
      remoteIsCalibrating,
      remoteCalibrationGrid,
      remoteEditingCorners,
      remoteEditingDividers,
      startRemoteCalibration,
      finishRemoteCalibration,
      cancelRemoteCalibration,
      rotateRemoteCorners,
      resetRemoteCalibration,
    ]
  )

  // -------------------------------------------------------------------------
  // Detection Results (from active source)
  // -------------------------------------------------------------------------
  const detection = useMemo(
    () => ({
      value: cameraSource === 'local' ? localCamera.currentDetectedValue : null, // TODO: Add remote detection
      confidence: cameraSource === 'local' ? localCamera.confidence : 0,
      isStable: cameraSource === 'local' ? localCamera.consecutiveFrames >= 3 : false,
      consecutiveFrames: cameraSource === 'local' ? localCamera.consecutiveFrames : 0,
    }),
    [cameraSource, localCamera]
  )

  // -------------------------------------------------------------------------
  // Context Value
  // -------------------------------------------------------------------------
  const contextValue: AbacusVisionContextValue = useMemo(
    () => ({
      cameraSource,
      setCameraSource,
      columnCount,
      setColumnCount,
      localCamera,
      remoteCamera: remoteCameraState,
      remoteCalibration: remoteCalibrationState,
      detection,
      onValueDetected,
      onConfigurationChange,
    }),
    [
      cameraSource,
      setCameraSource,
      columnCount,
      setColumnCount,
      localCamera,
      remoteCameraState,
      remoteCalibrationState,
      detection,
      onValueDetected,
      onConfigurationChange,
    ]
  )

  return (
    <AbacusVisionContext.Provider value={contextValue}>{children}</AbacusVisionContext.Provider>
  )
}

export default AbacusVisionContext