import { useEffect, useRef, useState, useCallback } from 'react';

// scrcpy 视频流逻辑：使用 scrcpy 协议实现流畅的实时画面
export function useScrcpyStream(currentDevice) {
  const [streamUrl, setStreamUrl] = useState(null);
  const [isStreaming, setIsStreaming] = useState(false);
  const streamIdRef = useRef(null);
  const activeDeviceRef = useRef(null);

  // 启动 scrcpy 流
  const startStream = useCallback(async (device) => {
    if (!device || !window.electronAPI || !window.electronAPI.startScrcpyStream) {
      console.warn('Scrcpy API 不可用或设备未连接');
      return;
    }

    try {
      // 停止之前的流（如果有）
      if (streamIdRef.current) {
        await stopStream();
      }

      const result = await window.electronAPI.startScrcpyStream(device);
      if (result?.success && result?.streamId) {
        streamIdRef.current = result.streamId;
        activeDeviceRef.current = device;
        
        // 创建 blob URL 用于 video 标签
        // 注意：实际实现中，streamId 会用于建立 WebSocket 或通过 IPC 传输视频数据
        // 这里先使用占位符，后续需要根据实际传输方式调整
        const url = `blob:scrcpy-${result.streamId}`;
        setStreamUrl(url);
        setIsStreaming(true);
      } else {
        console.error('启动 scrcpy 流失败:', result?.error);
      }
    } catch (err) {
      console.error('启动 scrcpy 流异常:', err);
    }
  }, []);

  // 停止 scrcpy 流
  const stopStream = useCallback(async () => {
    if (!streamIdRef.current) return;

    try {
      if (window.electronAPI && window.electronAPI.stopScrcpyStream) {
        await window.electronAPI.stopScrcpyStream(streamIdRef.current);
      }
      
      // 清理 blob URL
      if (streamUrl && streamUrl.startsWith('blob:')) {
        URL.revokeObjectURL(streamUrl);
      }
      
      streamIdRef.current = null;
      activeDeviceRef.current = null;
      setStreamUrl(null);
      setIsStreaming(false);
    } catch (err) {
      console.error('停止 scrcpy 流异常:', err);
    }
  }, [streamUrl]);

  // 监听设备变化
  useEffect(() => {
    if (currentDevice && currentDevice !== activeDeviceRef.current) {
      startStream(currentDevice);
    } else if (!currentDevice && activeDeviceRef.current) {
      stopStream();
    }

    return () => {
      if (activeDeviceRef.current) {
        stopStream();
      }
    };
  }, [currentDevice, startStream, stopStream]);

  return {
    streamUrl,
    isStreaming,
    startStream,
    stopStream,
  };
}

