import cv2, numpy as np

from Tbd.helper import  CameraObject

from PySide6.QtCore import Qt, QTimer, QSize
from PySide6.QtGui import QImage, QPixmap

from PySide6.QtWidgets import QWidget, QLabel, QVBoxLayout, QSizePolicy, QHBoxLayout, QLineEdit, QPushButton
from typing import List
from PySide6.QtWidgets import QScrollArea, QFrame


class CameraSetupWidget(QWidget):

    def __init__(self, cameraObject: CameraObject):
        super().__init__()
        
        self.cameraObject = cameraObject
        
        self.mainLayout = QHBoxLayout(self)

        self.frame_preview_widget = QLabel()
        self.preview_max_size = QSize(800, 600)
        self.frame_preview_widget.setMaximumSize(self.preview_max_size)
        self.camerOptionsLayout = QVBoxLayout()

        self.start_preview_button = QPushButton("Start")
        self.stop_preview_button = QPushButton("Stop")



        self.camerOptionsLayout.addWidget(self.start_preview_button)
        self.camerOptionsLayout.addWidget(self.stop_preview_button)

        self.mainLayout.addLayout(self.camerOptionsLayout)
        self.mainLayout.addWidget(self.frame_preview_widget)

        self.start_preview_button.clicked.connect(self._start_camera_preview)
        self.stop_preview_button.clicked.connect(self._stop_camera_preview)

        self.frame_update_timer = QTimer(self)
        self.frame_update_timer.timeout.connect(self._update_frame)
        

    def _start_camera_preview(self):
        if not self.cameraObject.open():
            return
        self.frame_update_timer.start(30)

    def _stop_camera_preview(self):
        self.frame_update_timer.stop()
        self.cameraObject.close()



    def _update_frame(self):
        if self.cameraObject.capture is None:
            return

        ok, frame = self.cameraObject.capture.read()
        if not ok or frame is None:
            return
        
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        height, width, ch = frame_rgb.shape
        qimg = QImage(frame_rgb.data, width, height, ch * width, QImage.Format_RGB888)
        pixmap = QPixmap.fromImage(qimg)
        pixmap = pixmap.scaled(
            self.frame_preview_widget.maximumSize(),
            Qt.KeepAspectRatio,
            Qt.SmoothTransformation,
        )
        self.frame_preview_widget.setPixmap(pixmap)
