# This is a CamiTK python action
#
# Video acquisition using OpenCV.
# 
# Creates a new RGB image component and continuously replaces its image data using the video feed.
# This action uses a timer to refresh the image.

import camitk
from PySide2.QtCore import QTimer
import cv2

def capture(self):
    ret, frame = self.capture_device.read()

    if not ret:
        camitk.warning("Error: Could not read frame.")
        return None
    else:
        # Convert the image from BGR to RGB
        rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        return rgb_frame

def capture_loop(self):
    rgb_frame = capture(self)
    if rgb_frame is not None and self.image_component:
        self.image_component.replaceImageData(rgb_frame)

def init(self:camitk.Action):
    self.timer:QTimer = None
    self.camera_index:int = 0
    self.image_component:camitk.ImageComponent = None
    self.setApplyButtonText("Start")

def process(self:camitk.Action):  
    if not self.timer:
        self.timer = QTimer()
        connected = self.timer.timeout.connect(lambda: capture_loop(self))
        
    if not self.timer.isActive():
        self.capture_device = cv2.VideoCapture(self.camera_index)
        if not self.capture_device.isOpened():
            camitk.warning(f"Error: Could not open capturing device #{self.camera_index}.")
            return

        rgb_frame = capture(self)
        if rgb_frame is not None and not self.image_component:
            self.image_component = camitk.newImageComponentFromNumpy(rgb_frame, "Webcam Video")
            self.refreshApplication()

        self.setApplyButtonText("Stop")    
        self.timer.start(10)
    else:      
        self.setApplyButtonText("Restart")    
        self.timer.stop()
        # Release the camera
        self.capture_device.release()
