#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
视频显示组件
用于显示视频帧和检测结果
"""

import cv2
import numpy as np
from PyQt5.QtWidgets import QLabel
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QImage, QPixmap, QPainter, QPen, QFont

class VideoWidget(QLabel):
    """视频显示组件"""
    
    def __init__(self):
        super().__init__()
        self.setMinimumSize(640, 480)
        self.setStyleSheet("border: 1px solid gray; background-color: black;")
        self.setAlignment(Qt.AlignCenter)
        self.setText("视频显示区域\n点击'开始检测'开始")
        self.setScaledContents(True)
        
    def update_frame(self, frame):
        """更新显示帧"""
        if frame is None:
            return
            
        # 转换BGR到RGB
        rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        h, w, ch = rgb_frame.shape
        bytes_per_line = ch * w
        
        # 创建QImage
        qt_image = QImage(rgb_frame.data, w, h, bytes_per_line, QImage.Format_RGB888)
        
        # 转换为QPixmap并显示
        pixmap = QPixmap.fromImage(qt_image)
        
        # 缩放以适应widget大小，保持宽高比
        scaled_pixmap = pixmap.scaled(
            self.size(), 
            Qt.KeepAspectRatio, 
            Qt.SmoothTransformation
        )
        
        self.setPixmap(scaled_pixmap)
        
    def paintEvent(self, event):
        """绘制事件"""
        super().paintEvent(event)
        
        # 如果没有图像，显示提示文本
        if not self.pixmap():
            painter = QPainter(self)
            painter.setPen(QPen(Qt.white))
            painter.setFont(QFont("Arial", 16))
            painter.drawText(self.rect(), Qt.AlignCenter, "视频显示区域\n点击'开始检测'开始")