# This is a script independent from CamiTK used to demonstrate
# how a CamiTK Python extension can use external code.
# This code is used by the action acquire_video_using_script
#
# Note:
# This script can be used independently from CamiTK (see __main__ below for an example)
# just run it using the extension virtual environment:
# .venv/bin/python video_capture_device

import cv2

class VideoCaptureDevice:
    max_camera_test_index:int = 10
        
    def __init__(self, camera_index, format=cv2.COLOR_BGR2RGB):
        self.capture_device:cv2.VideoCapture = None
        self.camera_index:int = camera_index
        self.format = format

    @staticmethod
    def list_available_cameras():
        available_cameras = []

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

        return available_cameras
    
    def is_started(self):
        return self.capture_device != None

    def start(self):
        self.capture_device = cv2.VideoCapture(self.camera_index)
        if not self.capture_device.isOpened():
            print(f"Error: Could not open capturing device #{self.camera_index}.")
            return

    def stop(self):
        self.capture_device.release()
        self.capture_device = None

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

        if not ret:
            print("Error: Could not read frame.")
            return None
        else:
            # Convert the image from BGR
            if self.format is not None:
                converted_frame = cv2.cvtColor(frame, self.format)
            else:
                converted_frame = frame
            return converted_frame

if __name__ == "__main__":
    available_cameras = VideoCaptureDevice.list_available_cameras()
    if (len(available_cameras)>1):
        camera = VideoCaptureDevice(available_cameras[0],None)
        camera.start()

        userInterruption = False
        cameraInterruption = False
        
        print("\nPress any key to stop video acquisition\n")
        while cv2.waitKey(1) == -1: # check if any key was pressed during 1 ms
            frame = camera.capture()
            if frame is None:
                print("Error: Could not read frame.")

            cv2.imshow('Camera Feed', frame)
    
        camera.stop()
        cv2.destroyAllWindows()
    else:
        print("No camera available. Exiting")