#!/usr/bin/env python3
"""
修复窗口显示问题 - 强制调整窗口大小
"""

import os
import sys
import time
import cv2
import numpy as np

os.environ["DISPLAY"] = ":0"

def window_fix_test():
    """修复窗口显示问题"""
    print("=== 窗口修复测试 ===")
    
    # 1. 获取接口
    sys.path.insert(0, '..')
    import ezai.go2 as go2
    
    robot = go2.Go2()
    robot.init()
    interface = robot.interface
    print(f"检测到接口: {interface}")
    
    # 2. 创建视频流
    pipe_path = "/tmp/window_fix_pipe"
    width, height = 1280, 720
    
    # 清理旧管道
    if os.path.exists(pipe_path):
        os.remove(pipe_path)
    
    # 创建管道
    os.mkfifo(pipe_path)
    print("命名管道已创建")
    
    # 启动GStreamer
    gst_cmd = (
        "exec gst-launch-1.0 udpsrc address=230.1.1.1 port=1720 multicast-iface=" + interface + " "
        "! application/x-rtp, media=video, encoding-name=H264 ! rtph264depay ! h264parse "
        "! avdec_h264 ! videoconvert ! video/x-raw,format=BGR,width=1280,height=720 "
        "! filesink location=" + pipe_path + " > /dev/null 2>&1 &"
    )
    
    print("启动GStreamer...")
    os.system(gst_cmd)
    time.sleep(3)
    
    try:
        print("开始读取视频...")
        frame_size = width * height * 3
        
        # 创建窗口并设置大小
        window_name = 'Go2视频流 (窗口修复版)'
        cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
        cv2.resizeWindow(window_name, width, height)
        print(f"创建窗口: {window_name}, 尺寸: {width}x{height}")
        
        with open(pipe_path, 'rb') as pipe:
            frame_count = 0
            
            while True:
                frame_data = pipe.read(frame_size)
                
                if len(frame_data) == frame_size:
                    # 转换为图像
                    frame = np.frombuffer(frame_data, dtype=np.uint8).reshape((height, width, 3))
                    
                    # 显示图像
                    cv2.imshow(window_name, frame)
                    frame_count += 1
                    
                    if frame_count == 1:
                        print(f"第一帧显示成功，图像尺寸: {frame.shape}")
                        # 再次确保窗口大小
                        cv2.resizeWindow(window_name, width, height)
                    
                    if frame_count % 30 == 0:
                        print(f"✅ 显示第 {frame_count} 帧")
                    
                    # 等待按键，确保窗口刷新
                    key = cv2.waitKey(30) & 0xFF  # 增加等待时间到30ms
                    if key == ord('q'):
                        break
                    elif key == ord('f'):
                        # 全屏切换
                        cv2.setWindowProperty(window_name, cv2.WND_PROP_FULLSCREEN, 
                                            cv2.WINDOW_FULLSCREEN)
                    elif key == ord('n'):
                        # 退出全屏
                        cv2.setWindowProperty(window_name, cv2.WND_PROP_FULLSCREEN, 
                                            cv2.WINDOW_NORMAL)
                        cv2.resizeWindow(window_name, width, height)
                else:
                    # 数据不完整时等待
                    cv2.waitKey(30)
                    
    except Exception as e:
        print(f"错误: {e}")
        import traceback
        traceback.print_exc()
    finally:
        # 清理
        os.system("pkill -f gst-launch")
        if os.path.exists(pipe_path):
            os.remove(pipe_path)
        cv2.destroyAllWindows()
        print("程序结束")

if __name__ == "__main__":
    window_fix_test()