import cv2

from PyQt6.QtCore import QTimer
from PyQt6.QtWidgets import QGraphicsScene



class VideoRecorder:
    def __init__(self, ) -> None:
        self._codec = cv2.VideoWriter_fourcc(*"XVID")  # Codec de video (XVID)
        self._recording = False
        self._timer = QTimer()
        self._timer.timeout.connect(self.capture_frame)


    def start_recording(self, output_path: str, scene: QGraphicsScene,  resolution: tuple[int, int], get_frame, fps: int = 30) -> None:
        """Start recording the video."""
        self._output_path = output_path
        self._scene = scene
        self._resolution = resolution
        self._fps = fps
        self._recording = True
        self._get_frame = get_frame
        self._video_writer = cv2.VideoWriter(self._output_path, self._codec, self._fps, self._resolution)
        self._timer.start(1000 // self._fps)  # Start the timer to capture frames at the specified FPS

        if not self._video_writer.isOpened():
            raise Exception(f"Could not open video writer with path: {self._output_path}")
   

    def capture_frame(self) -> None:
        """Capture a frame from the scene and write it to the video file."""
        frame = self._get_frame()

        if self._video_writer.isOpened():
            self._video_writer.write(frame)

    
    def stop_recording(self) -> None:
        """Stop recording the video."""
        self._recording = False
        self._timer.stop()
        if self._video_writer.isOpened():
            self._video_writer.release()

    def is_recording(self) -> bool:
        """Check if the video is currently being recorded."""
        return self._recording


