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

"""
GUI编辑模式功能测试
验证主程序中的GUI编辑模式是否正常工作
"""

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

import sys
from direct.showbase.ShowBase import ShowBase
from direct.gui.DirectGui import *
from panda3d.core import *

# 配置Panda3D
loadPrcFileData("", """
    win-size 800 600
    window-title GUI编辑模式测试
    framebuffer-multisample 1
    multisamples 2
""")

class GUIEditModeTest(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        
        print("=== GUI编辑模式功能测试 ===")
        
        # 设置背景色
        self.setBackgroundColor(0.2, 0.2, 0.3)
        
        # 初始化GUI相关变量
        self.gui_elements = []
        self.guiEditMode = False
        self.guiEditPanel = None
        self.currentGUITool = None
        self.selectedGUI = None
        
        # 尝试加载中文字体
        try:
            self.chinese_font = self.loader.loadFont('/usr/share/fonts/truetype/wqy/wqy-microhei.ttc')
            if not self.chinese_font:
                print("警告: 无法加载中文字体，将使用默认字体")
        except:
            print("警告: 无法加载中文字体，将使用默认字体")
            self.chinese_font = None
        
        # 创建测试说明
        self.createInstructions()
        
        # 自动进入GUI编辑模式进行测试
        self.enterGUIEditMode()
        
        print("\n=== 测试说明 ===")
        print("1. 应该能看到右侧的GUI编辑面板")
        print("2. 点击面板中的按钮选择不同工具")
        print("3. 点击场景中的位置应该能创建相应的GUI元素")
        print("4. 按ESC键退出")
        
        # 绑定退出键
        self.accept("escape", self.exitTest)
    
    def createInstructions(self):
        """创建说明文本"""
        self.title = OnscreenText(
            text="GUI编辑模式功能测试",
            pos=(0, 0.9),
            scale=0.08,
            fg=(1, 1, 1, 1),
            align=TextNode.ACenter,
            font=self.chinese_font if self.chinese_font else None
        )
        
        self.instruction = OnscreenText(
            text="右侧应该显示GUI编辑面板\n点击面板中的工具，然后点击场景创建GUI元素",
            pos=(0, -0.8),
            scale=0.05,
            fg=(1, 1, 0, 1),
            align=TextNode.ACenter,
            font=self.chinese_font if self.chinese_font else None
        )
    
    def enterGUIEditMode(self):
        """进入GUI编辑模式"""
        self.guiEditMode = True
        print("\n=== 进入GUI编辑模式 ===")
        
        # 创建GUI编辑面板
        self.createGUIEditPanel()
        
        print("GUI编辑模式已激活")
    
    def createGUIEditPanel(self):
        """创建GUI编辑面板"""
        # 创建主面板
        self.guiEditPanel = DirectFrame(
            pos=(0.85, 0, 0),
            frameSize=(-0.15, 0.15, -0.9, 0.9),
            frameColor=(0.1, 0.1, 0.1, 0.8),
            text="GUI编辑器",
            text_pos=(0, 0.85),
            text_scale=0.05,
            text_fg=(1, 1, 1, 1),
            text_font=self.chinese_font if self.chinese_font else None
        )
        
        # 创建工具按钮
        y_pos = 0.7
        spacing = 0.12
        
        # 2D GUI工具标签
        label_2d = DirectLabel(
            parent=self.guiEditPanel,
            text="2D GUI",
            pos=(0, 0, y_pos),
            scale=0.04,
            text_fg=(1, 1, 0, 1),
            frameColor=(0, 0, 0, 0),
            text_font=self.chinese_font if self.chinese_font else None
        )
        y_pos -= 0.08
        
        # 按钮工具
        btn_button = DirectButton(
            parent=self.guiEditPanel,
            text="按钮",
            pos=(0, 0, y_pos),
            scale=0.04,
            command=self.setGUICreateTool,
            extraArgs=["button"],
            frameColor=(0.2, 0.6, 0.8, 1),
            text_font=self.chinese_font if self.chinese_font else None
        )
        y_pos -= spacing
        
        # 标签工具
        btn_label = DirectButton(
            parent=self.guiEditPanel,
            text="标签",
            pos=(0, 0, y_pos),
            scale=0.04,
            command=self.setGUICreateTool,
            extraArgs=["label"],
            frameColor=(0.6, 0.8, 0.2, 1),
            text_font=self.chinese_font if self.chinese_font else None
        )
        y_pos -= spacing
        
        # 输入框工具
        btn_entry = DirectButton(
            parent=self.guiEditPanel,
            text="输入框",
            pos=(0, 0, y_pos),
            scale=0.04,
            command=self.setGUICreateTool,
            extraArgs=["entry"],
            frameColor=(0.8, 0.6, 0.2, 1),
            text_font=self.chinese_font if self.chinese_font else None
        )
        y_pos -= spacing
        
        # 3D GUI工具标签
        label_3d = DirectLabel(
            parent=self.guiEditPanel,
            text="3D GUI",
            pos=(0, 0, y_pos),
            scale=0.04,
            text_fg=(1, 1, 0, 1),
            frameColor=(0, 0, 0, 0),
            text_font=self.chinese_font if self.chinese_font else None
        )
        y_pos -= 0.08
        
        # 3D文本工具
        btn_3dtext = DirectButton(
            parent=self.guiEditPanel,
            text="3D文本",
            pos=(0, 0, y_pos),
            scale=0.04,
            command=self.setGUICreateTool,
            extraArgs=["3d_text"],
            frameColor=(0.8, 0.2, 0.6, 1),
            text_font=self.chinese_font if self.chinese_font else None
        )
        y_pos -= spacing
        
        # 虚拟屏幕工具
        btn_screen = DirectButton(
            parent=self.guiEditPanel,
            text="虚拟屏幕",
            pos=(0, 0, y_pos),
            scale=0.04,
            command=self.setGUICreateTool,
            extraArgs=["virtual_screen"],
            frameColor=(0.6, 0.2, 0.8, 1),
            text_font=self.chinese_font if self.chinese_font else None
        )
        y_pos -= spacing
        
        # 退出按钮
        btn_exit = DirectButton(
            parent=self.guiEditPanel,
            text="退出测试",
            pos=(0, 0, -0.8),
            scale=0.04,
            command=self.exitTest,
            frameColor=(0.8, 0.2, 0.2, 1),
            text_font=self.chinese_font if self.chinese_font else None
        )
        
        print("✓ GUI编辑面板创建成功")
    
    def setGUICreateTool(self, tool_type):
        """设置GUI创建工具"""
        self.currentGUITool = tool_type
        print(f"✓ 选择GUI创建工具: {tool_type}")
        
        # 绑定鼠标点击事件
        self.accept("mouse1", self.handleMouseClick)
    
    def handleMouseClick(self):
        """处理鼠标点击"""
        if not self.guiEditMode or not self.currentGUITool:
            return
            
        # 获取鼠标位置
        if not base.mouseWatcherNode.hasMouse():
            return
            
        mouse_x = base.mouseWatcherNode.getMouseX()
        mouse_y = base.mouseWatcherNode.getMouseY()
        
        print(f"鼠标点击位置: ({mouse_x:.2f}, {mouse_y:.2f})")
        
        # 创建GUI元素
        if self.currentGUITool == "button":
            self.createGUIButton((mouse_x * 10, 0, mouse_y * 10), f"按钮{len(self.gui_elements)}")
        elif self.currentGUITool == "label":
            self.createGUILabel((mouse_x * 10, 0, mouse_y * 10), f"标签{len(self.gui_elements)}")
        elif self.currentGUITool == "entry":
            self.createGUIEntry((mouse_x * 10, 0, mouse_y * 10), f"输入框{len(self.gui_elements)}")
        elif self.currentGUITool == "3d_text":
            self.createGUI3DText((mouse_x * 5, 0, mouse_y * 5), f"3D文本{len(self.gui_elements)}")
        elif self.currentGUITool == "virtual_screen":
            self.createGUIVirtualScreen((mouse_x * 5, 5, mouse_y * 5), text=f"屏幕{len(self.gui_elements)}")
    
    def createGUIButton(self, pos=(0, 0, 0), text="按钮"):
        """创建2D GUI按钮"""
        gui_pos = (pos[0] * 0.1, 0, pos[2] * 0.1)
        
        button = DirectButton(
            text=text,
            pos=gui_pos,
            scale=0.08,
            frameColor=(0.2, 0.6, 0.8, 1),
            text_font=self.chinese_font if self.chinese_font else None
        )
        
        self.gui_elements.append(button)
        print(f"✓ 创建GUI按钮: {text} 在位置 {gui_pos}")
        return button
    
    def createGUILabel(self, pos=(0, 0, 0), text="标签"):
        """创建2D GUI标签"""
        gui_pos = (pos[0] * 0.1, 0, pos[2] * 0.1)
        
        label = DirectLabel(
            text=text,
            pos=gui_pos,
            scale=0.06,
            frameColor=(0, 0, 0, 0),
            text_fg=(1, 1, 1, 1),
            text_font=self.chinese_font if self.chinese_font else None
        )
        
        self.gui_elements.append(label)
        print(f"✓ 创建GUI标签: {text} 在位置 {gui_pos}")
        return label
    
    def createGUIEntry(self, pos=(0, 0, 0), placeholder="输入框"):
        """创建2D GUI输入框"""
        gui_pos = (pos[0] * 0.1, 0, pos[2] * 0.1)
        
        entry = DirectEntry(
            text="",
            pos=gui_pos,
            scale=0.05,
            initialText=placeholder,
            numLines=1,
            width=12,
            focus=0
        )
        
        self.gui_elements.append(entry)
        print(f"✓ 创建GUI输入框: {placeholder} 在位置 {gui_pos}")
        return entry
    
    def createGUI3DText(self, pos=(0, 0, 0), text="3D文本"):
        """创建3D文本"""
        textNode = TextNode(f'3d-text-{len(self.gui_elements)}')
        textNode.setText(text)
        textNode.setAlign(TextNode.ACenter)
        if self.chinese_font:
            textNode.setFont(self.chinese_font)
        
        textNodePath = self.render.attachNewNode(textNode)
        textNodePath.setPos(*pos)
        textNodePath.setScale(0.5)
        textNodePath.setColor(1, 1, 0, 1)
        textNodePath.setBillboardAxis()
        
        self.gui_elements.append(textNodePath)
        print(f"✓ 创建3D文本: {text} 在位置 {pos}")
        return textNodePath
    
    def createGUIVirtualScreen(self, pos=(0, 0, 0), text="虚拟屏幕"):
        """创建3D虚拟屏幕"""
        from panda3d.core import CardMaker, TransparencyAttrib
        
        cm = CardMaker(f"virtual-screen-{len(self.gui_elements)}")
        cm.setFrame(-1, 1, -0.5, 0.5)
        virtualScreen = self.render.attachNewNode(cm.generate())
        virtualScreen.setPos(*pos)
        virtualScreen.setColor(0.2, 0.2, 0.2, 0.8)
        virtualScreen.setTransparency(TransparencyAttrib.MAlpha)
        
        # 添加文本
        screenText = TextNode(f'screen-text-{len(self.gui_elements)}')
        screenText.setText(text)
        screenText.setAlign(TextNode.ACenter)
        if self.chinese_font:
            screenText.setFont(self.chinese_font)
        screenTextNP = virtualScreen.attachNewNode(screenText)
        screenTextNP.setPos(0, 0.01, 0)
        screenTextNP.setScale(0.3)
        screenTextNP.setColor(0, 1, 0, 1)
        
        self.gui_elements.append(virtualScreen)
        print(f"✓ 创建虚拟屏幕: {text} 在位置 {pos}")
        return virtualScreen
    
    def exitTest(self):
        """退出测试"""
        print(f"\n=== 测试完成 ===")
        print(f"总共创建了 {len(self.gui_elements)} 个GUI元素")
        print("如果能看到GUI编辑面板并成功创建元素，说明功能正常!")
        self.userExit()

def main():
    """主函数"""
    print("启动GUI编辑模式功能测试...")
    print("这将测试主程序中新增的GUI编辑模式功能")
    
    # 创建并运行测试
    app = GUIEditModeTest()
    app.run()

if __name__ == "__main__":
    main() 