#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Qt环境专用GUI测试
"""

import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLabel
from PyQt5.QtCore import Qt
from QMeta3D.QMeta3DWidget import QMeta3DWidget
from QMeta3D.Meta3DWorld import Meta3DWorld
from direct.gui.DirectGui import *
from direct.gui.OnscreenText import OnscreenText
from panda3d.core import *

class QtOnlyWorld(Meta3DWorld):
    def __init__(self):
        super().__init__()
        
        print("=== 专用Qt环境测试 ===")
        self.setBackgroundColor(0.2, 0.2, 0.3)
        
        # 检查环境差异
        print(f"基类: {self.__class__.__bases__}")
        print(f"render2d: {self.render2d}")
        print(f"aspect2d: {self.aspect2d}")
        print(f"窗口类型: {type(self.win) if hasattr(self, 'win') else 'None'}")
        
        # 检查更多属性
        if hasattr(self, 'win'):
            print(f"窗口: {self.win}")
            print(f"窗口大小: {self.win.getXSize()} x {self.win.getYSize()}")
        
        print(f"图形引擎: {self.graphicsEngine}")
        print(f"显示区域数量: {self.win.getNumDisplayRegions() if hasattr(self, 'win') else 'None'}")
        
        # 延迟创建GUI
        self.taskMgr.doMethodLater(0.5, self.createTestGUI, "create-gui")
    
    def createTestGUI(self, task=None):
        """创建测试GUI"""
        print("\n--- Qt环境创建GUI ---")
        
        # 检查2D渲染系统状态
        print(f"render2d可用: {self.render2d is not None}")
        print(f"aspect2d可用: {self.aspect2d is not None}")
        print(f"camera2d可用: {hasattr(self, 'camera2d') and self.camera2d is not None}")
        
        if hasattr(self, 'camera2d'):
            print(f"camera2d位置: {self.camera2d.getPos()}")
            print(f"camera2d朝向: {self.camera2d.getHpr()}")
        
        # 创建标题文本 - 这通常能工作
        try:
            self.title = OnscreenText(
                text="Qt Only Test",
                pos=(0, 0.8),
                scale=0.08,
                fg=(1, 1, 1, 1),
                align=TextNode.ACenter
            )
            print(f"✓ 标题创建成功: {self.title}")
            print(f"  标题父节点: {self.title.getParent()}")
        except Exception as e:
            print(f"✗ 标题创建失败: {str(e)}")
        
        # 创建DirectButton - 问题可能在这里
        try:
            self.testButton = DirectButton(
                text="Test Button",
                pos=(0, 0, 0),
                scale=0.1,
                command=self.onButtonClick,
                frameColor=(1, 0, 0, 1),
                text_font=None,
                rolloverSound=None,
                clickSound=None
            )
            print(f"✓ 按钮创建成功: {self.testButton}")
            print(f"  按钮父节点: {self.testButton.getParent()}")
            print(f"  按钮位置: {self.testButton.getPos()}")
            print(f"  按钮隐藏状态: {self.testButton.isHidden()}")
            
            # 检查按钮的PGButton节点
            pg_button = self.testButton.node()
            print(f"  PGButton节点: {pg_button}")
            print(f"  PGButton类型: {type(pg_button)}")
            
        except Exception as e:
            print(f"✗ 按钮创建失败: {str(e)}")
            import traceback
            traceback.print_exc()
        
        # 检查aspect2d的子节点
        print(f"\naspect2d子节点数量: {self.aspect2d.getNumChildren()}")
        for i in range(self.aspect2d.getNumChildren()):
            child = self.aspect2d.getChild(i)
            print(f"  子节点 {i}: {child}")
        
        # 尝试手动强制渲染
        try:
            if hasattr(self, 'graphicsEngine'):
                print("\n尝试强制渲染...")
                self.graphicsEngine.renderFrame()
                print("强制渲染完成")
        except Exception as e:
            print(f"强制渲染失败: {str(e)}")
        
        return task.done if task else None
    
    def onButtonClick(self):
        print("🎯 Qt环境按钮被点击了！")

def main():
    print("启动Qt环境专用测试...")
    
    app = QApplication(sys.argv)
    
    # 创建主窗口
    mainWindow = QMainWindow()
    mainWindow.setWindowTitle("Qt专用GUI测试")
    mainWindow.setGeometry(100, 100, 800, 600)
    
    # 创建布局
    centralWidget = QWidget()
    layout = QVBoxLayout(centralWidget)
    
    # 添加说明
    label = QLabel("Qt环境DirectGUI专用测试 - 检查控制台输出")
    label.setAlignment(Qt.AlignCenter)
    label.setStyleSheet("background-color: lightcoral; padding: 10px;")
    layout.addWidget(label)
    
    # 创建世界
    world = QtOnlyWorld()
    
    # 创建Panda3D部件
    pandaWidget = QMeta3DWidget(world)
    layout.addWidget(pandaWidget)
    
    mainWindow.setCentralWidget(centralWidget)
    mainWindow.show()
    
    print("\nQt环境窗口已显示")
    print("如果能看到红色按钮，说明Qt环境下的DirectGUI是正常的")
    print("如果看不到按钮但有标题，说明DirectButton在Qt环境中有问题")
    
    return app.exec_()

if __name__ == "__main__":
    main() 