# This is a CamiTK python action
#
# Acquire an image using a camera.
# During startup, this action checks the cameras available
# to the computer and prepares a list with their index. 
# The user chooses the camera id in the list, and clicks "Apply()"
# to acquire an image.
# After an acquisition, the user can select the newly created image
# component to start video acquisition using the 'Video Capture' action.
import camitk
import cv2
import numpy as np

def list_available_cameras(max_cameras=10):
    available_cameras = []

    for index in range(max_cameras):
        cap = cv2.VideoCapture(index)
        if cap.isOpened():
            available_cameras.append(index)
            cap.release()

    return available_cameras
        
def capture_image_from_camera(camera_index = 0):
    # Initialize the camera using the given video device
    cap = cv2.VideoCapture(camera_index)

    if not cap.isOpened():
        camitk.warning(f"Error: Could not open capturing device #{camera_index}.")
        return None

    # Capture frame-by-frame
    ret, frame = cap.read()

    if not ret:
        camitk.warning("Error: Could not read frame.")
        return None

    # Convert the image from BGR to RGB
    rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    
    # Release the camera
    cap.release()

    return rgb_frame

def init(self:camitk.Action):
    available_cameras = list_available_cameras()
    
    if available_cameras:
        prop = camitk.Property("Video Capture Device", available_cameras[0], "Camera to use for image acquisition (0 is usually the PC webcam)", "")
        prop.setAttribute("enumNames", available_cameras);
        prop.setEnumTypeName(r'VideoCaptureDeviceId');
        self.addParameter(prop)
        self.setApplyButtonText("Take Snapshot")
    else:
        print("No cameras found.")
        return
    
    selected_camera = self.getParameterValue("Video Capture Device")
    enumValues = self.getProperty("Video Capture Device").getAttribute("enumNames")   
    camitk.info(f"init() selected camera: {selected_camera} → {enumValues[selected_camera]}")

def process(self:camitk.Action):
    camitk.info(f"process()")
    selected_camera = self.getParameterValue("Video Capture Device")
    enumValues = self.getProperty("Video Capture Device").getAttribute("enumNames")   
    camitk.info(f"process() selected camera: {selected_camera} → {enumValues[selected_camera]}")
    image = capture_image_from_camera(int(enumValues[selected_camera]))

    if image is not None:
        new_image_component = camitk.newImageComponentFromNumpy(image, "Webcam Image")
    
    self.refreshApplication() # similar to what would be done in C++
    # or camitk.refresh()
