import cv2
from pywt.version import release


class cvStreamer():
    def __init__(self, idx):
        self.cap = cv2.VideoCapture(idx)
        self.idx = idx

    def isOpened(self):
        isOpen = self.cap.isOpened()

        if not isOpen:
            self.release()
        else:
            print(f"usb cam open at {self.idx}")


        return isOpen

    def release(self):
        self.cap.release()

    def get_frame(self):
        _, frame = self.cap.read()

        # Get the original dimensions of the frame
        height, width = frame.shape[:2]

        # Define the maximum dimensions
        max_width = 1920
        max_height = 1080

        # Calculate the aspect ratio
        aspect_ratio = width / height

        # Resize the frame if it exceeds the maximum dimensions
        if width > max_width or height > max_height:
            if aspect_ratio > 1:  # Landscape orientation
                new_width = max_width
                new_height = int(new_width / aspect_ratio)
            else:  # Portrait orientation
                new_height = max_height
                new_width = int(new_height * aspect_ratio)

            # Resize the frame
            frame = cv2.resize(frame, (new_width, new_height))

        return frame

    def __del__(self):
        self.release()