class ToolManager:
    """工具管理器 - 管理编辑器工具状态"""

    def __init__(self, world):
        """初始化工具管理器"""
        self.world = world
        self.currentTool = "选择"  # 默认工具为选择工具
        print(f"当前工具: {self.currentTool}")

    def setCurrentTool(self, tool):
        """设置当前工具"""
        self.currentTool = tool

        print(f"\n=== 工具切换 ===")
        print(f"当前工具: {tool}")
        print(f"选中节点: {self.world.selection.selectedNode.getName() if self.world.selection.selectedNode else '无'}")

        # 根据工具类型启用对应的方法
        if tool == "选择":
            print(f"当前工具为：{tool}")
            #self._enableSelectionTool()
        elif tool == "移动":
            print(f"当前工具为：{tool}")
            #self._enableMoveTool()
        elif tool == "旋转":
            print(f"当前工具为：{tool}")
            #self._enableRotateTool()
        elif tool == "缩放":
            print(f"当前工具为：{tool}")
            #self._enableScaleTool()
        elif tool == "光照编辑":
            print(f"当前工具为：{tool}")
            self.launch_day_time_editor()
        elif tool == "图形编辑":
            print(f"当前工具为：{tool}")
            self.launch_plugin_configurator()

            # 坐标轴现在始终跟随选中状态，不再依赖工具类型

    def getCurrentTool(self):
        """获取当前工具"""
        return self.currentTool

    def isSelectionTool(self):
        """检查当前是否是选择工具"""
        return self.currentTool == "选择"

    def isMoveTool(self):
        """检查当前是否是移动工具"""
        return self.currentTool == "移动"

    def isRotateTool(self):
        """检查当前是否是旋转工具"""
        return self.currentTool == "旋转"

    def isScaleTool(self):
        """检查当前是否是缩放工具"""
        return self.currentTool == "缩放"

    def isDayTimeEditorTool(self):
        """光照"""
        return self.currentTool=="光照编辑"
    def isPlugincongiguratorTool(self):
        """检查当前是否是图形编辑工具"""
        return self.currentTool == "图形编辑"

    def launch_day_time_editor(self):

        # 检查是否已经启动
        if hasattr(self, '_day_time_editor_process') and self._day_time_editor_process:
            if self._day_time_editor_process.poll() is None:  # 进程仍在运行
                print("Day Time Editor 已经在运行")
                return True
        import subprocess
        import os
        import sys

        try:
            if not hasattr(self.world,'render_pipeline') or not self.world.render_pipeline:
                print("错误：renderpipeline未初始化")
                return False

            base_path = self.world.render_pipeline.mount_mgr.base_path
            editor_path = os.path.join(base_path,"toolkit/day_time_editor/main.py")

            if not os.path.exists(editor_path):
                print("错误文件不存在")
                return False

            self._day_time_editor_process = subprocess.Popen([sys.executable, editor_path])
            print("Day Time Editor 已启动")
            return True
        except Exception as e:
            print(f"启动 time editor失败")

    def openSunLightingTool(self):
        """打开太阳光照系统工具的便捷方法"""
        return self.launch_day_time_editor()

    def launch_plugin_configurator(self):
        """启动插件配置器"""
        import subprocess
        import os
        import sys

        try:
            # 检查是否已经有进程在运行
            if hasattr(self, '_plugin_configurator_process') and self._plugin_configurator_process:
                # 检查进程是否仍在运行
                if self._plugin_configurator_process.poll() is None:
                    print("⚠️ 插件配置器已经在运行中，无需重复启动")
                    # 尝试将窗口置于前台（在某些系统上可能有效）
                    try:
                        # 在Windows上可以尝试激活窗口
                        if os.name == 'nt':
                            import win32gui
                            import win32con
                            def enum_windows_callback(hwnd, pid):
                                if win32gui.GetWindowThreadProcessId(hwnd)[1] == pid:
                                    win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
                                    win32gui.SetForegroundWindow(hwnd)
                                    return False
                                return True
                            win32gui.EnumWindows(enum_windows_callback, self._plugin_configurator_process.pid)
                    except ImportError:
                        pass  # win32gui不可用，跳过窗口激活
                    except Exception as e:
                        print(f"尝试激活窗口失败: {e}")
                    return True
                else:
                    # 进程已结束，清理引用
                    print("🔄 检测到之前的插件配置器进程已结束，准备启动新进程")
                    self._plugin_configurator_process = None

            if not self.world.render_pipeline:
                print("❌ 错误：RenderPipeline未初始化")
                return False

            base_path = self.world.render_pipeline.mount_mgr.base_path
            editor_path = os.path.join(base_path, "toolkit/plugin_configurator/main.py")

            if not os.path.exists(editor_path):
                print(f"❌ 错误：插件配置器文件不存在: {editor_path}")
                return False

            print("🚀 启动插件配置器...")
            self._plugin_configurator_process = subprocess.Popen([sys.executable, editor_path])
            print("✅ 插件配置器已启动")
            return True

        except Exception as e:
            print(f"❌ 启动插件配置器失败: {e}")
            return False
