import {useCallback,useEffect,useRef,useState} from 'react'; import type {Sensor} from './contracts'; import {observationSession} from './observationStart'; import {previewReconnect,previewRetryDelay} from './previewReconnect'; /** Starts are serialized; opt-in observation recovery always rereads device state. */ export function useObservationStart(device:Sensor,enabled:boolean,active:boolean,start:()=>Promise,recover=false){ const scope=observationSession(device),latest=useRef({scope,enabled,start});latest.current={scope,enabled,start}; const mounted=useRef(false),attempted=useRef(''),running=useRef(false); const attempts=useRef(0),[attempt,setAttempt]=useState(0); const [pending,setPending]=useState(false),[error,setError]=useState(''); useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]); useEffect(()=>{attempts.current=0;setError('');},[scope]); const retry=useCallback(async()=>{ const value=latest.current;if(!value.enabled||running.current)return; attempted.current=value.scope;running.current=true;setPending(true);setError('');setAttempt(v=>v+1); try{await value.start();}catch(reason){if(mounted.current&&latest.current.scope===value.scope)setError(reason instanceof Error?reason.message:'Не удалось начать просмотр.');} finally{running.current=false;if(mounted.current)setPending(false);} },[]); useEffect(()=>{ if(!enabled){attempted.current='';return;} if(active){attempted.current=scope;attempts.current=0;setError('');return;} if(attempted.current!==scope)void retry(); },[scope,enabled,active,retry,pending]); useEffect(()=>{ if(!recover||!enabled||active||pending||!error)return; const timer=previewReconnect({visible:()=>document.visibilityState!=='hidden',retry:()=>void retry(),now:()=>performance.now(),schedule:(run,delay)=>setTimeout(run,delay),cancel:id=>clearTimeout(id as ReturnType)}); timer.schedule(previewRetryDelay(attempts.current++)); const visibility=()=>{if(document.visibilityState==='hidden')timer.pause();else timer.resume();}; const online=()=>timer.recovered(); document.addEventListener('visibilitychange',visibility);window.addEventListener('online',online); return()=>{timer.dispose();document.removeEventListener('visibilitychange',visibility);window.removeEventListener('online',online);}; },[scope,enabled,active,pending,error,attempt,recover,retry]); return {pending,error,retry}; }