"""
匹配编辑器模块
提供图形界面配置匹配参数
"""

import time
from typing import Dict, Any, List, Optional

class MatchEditor:
    """
    匹配编辑器
    提供图形界面配置匹配参数
    """
    
    def __init__(self, plugin):
        """
        初始化匹配编辑器
        
        Args:
            plugin: 匹配系统插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 编辑器配置
        self.editor_config = {
            "enable_editor": True,
            "enable_realtime_monitoring": True,
            "enable_performance_display": True,
            "enable_config_editor": True,
            "enable_statistics_display": True,
            "refresh_interval": 1.0,
            "max_data_points": 100
        }
        
        # 编辑器状态
        self.editor_state = {
            "is_visible": False,
            "last_update": 0.0,
            "active_tab": "overview",
            "selected_queue": None,
            "selected_algorithm": None
        }
        
        # UI组件
        self.ui_components = {
            "main_window": None,
            "tabs": {},
            "panels": {},
            "charts": {},
            "controls": {}
        }
        
        # 编辑器统计
        self.editor_stats = {
            "updates": 0,
            "ui_refreshes": 0,
            "data_points": 0,
            "editor_errors": 0
        }
        
        # 实时数据缓存
        self.realtime_data = {
            "performance_metrics": {},
            "queue_data": {},
            "match_data": {},
            "algorithm_stats": {},
            "system_stats": {}
        }
        
        # 回调函数
        self.editor_callbacks = {
            "ui_updated": [],
            "data_refreshed": [],
            "config_changed": [],
            "editor_error": []
        }
        
        # 时间戳记录
        self.last_ui_update = 0.0
        self.last_data_refresh = 0.0
        
        print("✓ 匹配编辑器已创建")
        
    def initialize(self) -> bool:
        """
        初始化匹配编辑器
        
        Returns:
            是否初始化成功
        """
        try:
            print("正在初始化匹配编辑器...")
            
            # 初始化UI组件（模拟）
            self._initialize_ui_components()
            
            self.initialized = True
            print("✓ 匹配编辑器初始化完成")
            return True
            
        except Exception as e:
            print(f"✗ 匹配编辑器初始化失败: {e}")
            self.editor_stats["editor_errors"] += 1
            import traceback
            traceback.print_exc()
            return False
            
    def _initialize_ui_components(self):
        """初始化UI组件"""
        try:
            # 创建主窗口
            self.ui_components["main_window"] = {
                "title": "匹配系统编辑器",
                "size": (1200, 800),
                "position": (100, 100)
            }
            
            # 创建标签页
            self.ui_components["tabs"] = {
                "overview": {"name": "概览", "icon": "dashboard"},
                "queues": {"name": "队列", "icon": "queue"},
                "matches": {"name": "匹配", "icon": "gamepad"},
                "algorithms": {"name": "算法", "icon": "calculate"},
                "rooms": {"name": "房间", "icon": "meeting_room"},
                "config": {"name": "配置", "icon": "settings"},
                "statistics": {"name": "统计", "icon": "bar_chart"}
            }
            
            # 创建面板
            self.ui_components["panels"] = {
                "system_status": {"title": "系统状态", "visible": True},
                "performance": {"title": "性能指标", "visible": True},
                "queues_list": {"title": "队列列表", "visible": True},
                "matches_list": {"title": "匹配列表", "visible": True},
                "algorithm_stats": {"title": "算法统计", "visible": True}
            }
            
            print("✓ UI组件已初始化")
            
        except Exception as e:
            print(f"✗ UI组件初始化失败: {e}")
            self.editor_stats["editor_errors"] += 1
            
    def enable(self) -> bool:
        """
        启用匹配编辑器
        
        Returns:
            是否启用成功
        """
        try:
            if not self.initialized:
                print("✗ 匹配编辑器未初始化")
                return False
                
            self.enabled = True
            print("✓ 匹配编辑器已启用")
            return True
            
        except Exception as e:
            print(f"✗ 匹配编辑器启用失败: {e}")
            self.editor_stats["editor_errors"] += 1
            import traceback
            traceback.print_exc()
            return False
            
    def disable(self):
        """禁用匹配编辑器"""
        try:
            self.enabled = False
            
            # 隐藏UI
            self.hide_editor()
            
            print("✓ 匹配编辑器已禁用")
            
        except Exception as e:
            print(f"✗ 匹配编辑器禁用失败: {e}")
            self.editor_stats["editor_errors"] += 1
            import traceback
            traceback.print_exc()
            
    def finalize(self):
        """清理匹配编辑器资源"""
        try:
            # 禁用匹配编辑器
            if self.enabled:
                self.disable()
                
            # 清理回调
            self.editor_callbacks.clear()
            
            self.initialized = False
            print("✓ 匹配编辑器资源已清理")
            
        except Exception as e:
            print(f"✗ 匹配编辑器资源清理失败: {e}")
            import traceback
            traceback.print_exc()
            
    def update(self, dt: float):
        """
        更新匹配编辑器状态
        
        Args:
            dt: 时间增量（秒）
        """
        try:
            if not self.enabled:
                return
                
            current_time = time.time()
            
            # 定期刷新UI
            if current_time - self.last_ui_update >= self.editor_config["refresh_interval"]:
                self._refresh_ui()
                self.last_ui_update = current_time
                
            # 定期更新数据
            if current_time - self.last_data_refresh >= 0.5:  # 每0.5秒更新一次数据
                self._update_realtime_data()
                self.last_data_refresh = current_time
                
            self.editor_state["last_update"] = current_time
            
        except Exception as e:
            print(f"✗ 匹配编辑器更新失败: {e}")
            self.editor_stats["editor_errors"] += 1
            import traceback
            traceback.print_exc()
            
    def _refresh_ui(self):
        """刷新UI"""
        try:
            # 更新UI组件状态
            self._update_ui_components()
            
            # 更新统计信息
            self.editor_stats["ui_refreshes"] += 1
            
            # 触发UI更新回调
            self._trigger_editor_callback("ui_updated", {
                "timestamp": time.time()
            })
            
        except Exception as e:
            print(f"✗ UI刷新失败: {e}")
            self.editor_stats["editor_errors"] += 1
            
    def _update_ui_components(self):
        """更新UI组件"""
        try:
            # 更新系统状态面板
            system_stats = {}
            if self.plugin.match_manager:
                system_stats.update(self.plugin.match_manager.get_match_stats())
            if self.plugin.queue_manager:
                system_stats.update(self.plugin.queue_manager.get_queue_stats())
            if self.plugin.algorithm_manager:
                system_stats.update(self.plugin.algorithm_manager.get_algorithm_stats())
                
            self.ui_components["panels"]["system_status"]["data"] = system_stats
            
            # 更新队列列表面板
            if self.plugin.queue_manager:
                queues = self.plugin.queue_manager.get_queue_info()
                self.ui_components["panels"]["queues_list"]["data"] = queues
                
            # 更新匹配列表面板
            if self.plugin.match_manager:
                match_stats = self.plugin.match_manager.get_match_stats()
                self.ui_components["panels"]["matches_list"]["data"] = match_stats
                
            # 更新算法统计面板
            if self.plugin.algorithm_manager:
                algorithm_stats = self.plugin.algorithm_manager.get_algorithm_stats()
                self.ui_components["panels"]["algorithm_stats"]["data"] = algorithm_stats
                
        except Exception as e:
            print(f"✗ UI组件更新失败: {e}")
            self.editor_stats["editor_errors"] += 1
            
    def _update_realtime_data(self):
        """更新实时数据"""
        try:
            current_time = time.time()
            
            # 更新性能指标
            if self.plugin.monitor:
                metrics = self.plugin.monitor.get_performance_metrics()
                self.realtime_data["performance_metrics"] = metrics
                
            # 更新队列数据
            if self.plugin.queue_manager:
                queue_info = self.plugin.queue_manager.get_queue_info()
                self.realtime_data["queue_data"] = queue_info
                
            # 更新匹配数据
            if self.plugin.match_manager:
                match_stats = self.plugin.match_manager.get_match_stats()
                self.realtime_data["match_data"] = match_stats
                
            # 更新算法统计
            if self.plugin.algorithm_manager:
                algorithm_stats = self.plugin.algorithm_manager.get_algorithm_stats()
                self.realtime_data["algorithm_stats"] = algorithm_stats
                
            # 更新系统统计
            system_stats = {}
            if self.plugin.config_manager:
                system_stats["config"] = self.plugin.config_manager.get_config_stats()
            if self.plugin.event_handler:
                system_stats["events"] = self.plugin.event_handler.get_event_stats()
                
            self.realtime_data["system_stats"] = system_stats
            
            # 触发数据刷新回调
            self._trigger_editor_callback("data_refreshed", {
                "data": self.realtime_data,
                "timestamp": current_time
            })
            
        except Exception as e:
            print(f"✗ 实时数据更新失败: {e}")
            self.editor_stats["editor_errors"] += 1
            
    def show_editor(self):
        """显示编辑器"""
        try:
            self.editor_state["is_visible"] = True
            print("✓ 匹配编辑器已显示")
            
            # 刷新数据
            self._update_realtime_data()
            
        except Exception as e:
            print(f"✗ 编辑器显示失败: {e}")
            self.editor_stats["editor_errors"] += 1
            
    def hide_editor(self):
        """隐藏编辑器"""
        try:
            self.editor_state["is_visible"] = False
            print("✓ 匹配编辑器已隐藏")
            
        except Exception as e:
            print(f"✗ 编辑器隐藏失败: {e}")
            self.editor_stats["editor_errors"] += 1
            
    def switch_tab(self, tab_name: str):
        """
        切换标签页
        
        Args:
            tab_name: 标签页名称
        """
        try:
            if tab_name in self.ui_components["tabs"]:
                self.editor_state["active_tab"] = tab_name
                print(f"✓ 切换到标签页: {tab_name}")
            else:
                print(f"✗ 无效的标签页: {tab_name}")
                
        except Exception as e:
            print(f"✗ 标签页切换失败: {e}")
            self.editor_stats["editor_errors"] += 1
            
    def select_queue(self, queue_name: str):
        """
        选择队列
        
        Args:
            queue_name: 队列名称
        """
        try:
            self.editor_state["selected_queue"] = queue_name
            print(f"✓ 选择队列: {queue_name}")
            
        except Exception as e:
            print(f"✗ 队列选择失败: {e}")
            self.editor_stats["editor_errors"] += 1
            
    def select_algorithm(self, algorithm_name: str):
        """
        选择算法
        
        Args:
            algorithm_name: 算法名称
        """
        try:
            self.editor_state["selected_algorithm"] = algorithm_name
            print(f"✓ 选择算法: {algorithm_name}")
            
        except Exception as e:
            print(f"✗ 算法选择失败: {e}")
            self.editor_stats["editor_errors"] += 1
            
    def update_config(self, section: str, key: str, value: Any) -> bool:
        """
        更新配置
        
        Args:
            section: 配置节
            key: 配置键
            value: 配置值
            
        Returns:
            是否更新成功
        """
        try:
            # 通过配置管理器更新配置
            if self.plugin.config_manager:
                result = self.plugin.config_manager.set_config(section, key, value)
                
                if result:
                    self.editor_stats["updates"] += 1
                    
                    # 触发配置更改回调
                    self._trigger_editor_callback("config_changed", {
                        "section": section,
                        "key": key,
                        "value": value,
                        "timestamp": time.time()
                    })
                    
                    print(f"✓ 配置已更新: {section}.{key} = {value}")
                    return True
                else:
                    print(f"✗ 配置更新失败: {section}.{key}")
                    return False
            else:
                print("✗ 配置管理器不可用")
                return False
                
        except Exception as e:
            print(f"✗ 配置更新失败: {e}")
            self.editor_stats["editor_errors"] += 1
            return False
            
    def get_editor_stats(self) -> Dict[str, Any]:
        """
        获取编辑器统计信息
        
        Returns:
            编辑器统计字典
        """
        return {
            "state": self.editor_state.copy(),
            "stats": self.editor_stats.copy(),
            "config": self.editor_config.copy(),
            "ui_components": len(self.ui_components["tabs"])
        }
        
    def reset_stats(self):
        """重置编辑器统计信息"""
        try:
            self.editor_stats = {
                "updates": 0,
                "ui_refreshes": 0,
                "data_points": 0,
                "editor_errors": 0
            }
            print("✓ 编辑器统计信息已重置")
        except Exception as e:
            print(f"✗ 编辑器统计信息重置失败: {e}")
            
    def set_editor_config(self, config: Dict[str, Any]) -> bool:
        """
        设置编辑器配置
        
        Args:
            config: 编辑器配置字典
            
        Returns:
            是否设置成功
        """
        try:
            self.editor_config.update(config)
            print(f"✓ 编辑器配置已更新: {self.editor_config}")
            return True
        except Exception as e:
            print(f"✗ 编辑器配置设置失败: {e}")
            return False
            
    def get_editor_config(self) -> Dict[str, Any]:
        """
        获取编辑器配置
        
        Returns:
            编辑器配置字典
        """
        return self.editor_config.copy()
        
    def get_realtime_data(self) -> Dict[str, Any]:
        """
        获取实时数据
        
        Returns:
            实时数据字典
        """
        return self.realtime_data.copy()
        
    def export_data(self, data_type: str, file_path: str) -> bool:
        """
        导出数据
        
        Args:
            data_type: 数据类型
            file_path: 导出文件路径
            
        Returns:
            是否导出成功
        """
        try:
            import json
            import os
            
            # 创建导出目录
            export_dir = os.path.dirname(file_path)
            if not os.path.exists(export_dir):
                os.makedirs(export_dir)
                
            # 获取要导出的数据
            export_data = None
            if data_type == "performance":
                export_data = self.realtime_data["performance_metrics"]
            elif data_type == "queues":
                export_data = self.realtime_data["queue_data"]
            elif data_type == "matches":
                export_data = self.realtime_data["match_data"]
            elif data_type == "algorithms":
                export_data = self.realtime_data["algorithm_stats"]
            elif data_type == "system":
                export_data = self.realtime_data["system_stats"]
            elif data_type == "all":
                export_data = self.realtime_data
            else:
                print(f"✗ 不支持的数据类型: {data_type}")
                return False
                
            # 导出数据
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(export_data, f, indent=2, ensure_ascii=False, default=str)
                
            print(f"✓ 数据已导出到: {file_path}")
            return True
            
        except Exception as e:
            print(f"✗ 数据导出失败: {e}")
            self.editor_stats["editor_errors"] += 1
            return False
            
    def _trigger_editor_callback(self, callback_type: str, data: Dict[str, Any]):
        """
        触发编辑器回调
        
        Args:
            callback_type: 回调类型
            data: 回调数据
        """
        try:
            if callback_type in self.editor_callbacks:
                for callback in self.editor_callbacks[callback_type]:
                    try:
                        callback(data)
                    except Exception as e:
                        print(f"✗ 编辑器回调执行失败: {callback_type} - {e}")
        except Exception as e:
            print(f"✗ 编辑器回调触发失败: {e}")
            
    def register_editor_callback(self, callback_type: str, callback: callable):
        """
        注册编辑器回调
        
        Args:
            callback_type: 回调类型
            callback: 回调函数
        """
        try:
            if callback_type in self.editor_callbacks:
                self.editor_callbacks[callback_type].append(callback)
                print(f"✓ 编辑器回调已注册: {callback_type}")
            else:
                print(f"✗ 无效的回调类型: {callback_type}")
        except Exception as e:
            print(f"✗ 编辑器回调注册失败: {e}")
            
    def unregister_editor_callback(self, callback_type: str, callback: callable):
        """
        注销编辑器回调
        
        Args:
            callback_type: 回调类型
            callback: 回调函数
        """
        try:
            if callback_type in self.editor_callbacks:
                if callback in self.editor_callbacks[callback_type]:
                    self.editor_callbacks[callback_type].remove(callback)
                    print(f"✓ 编辑器回调已注销: {callback_type}")
            else:
                print(f"✗ 无效的回调类型: {callback_type}")
        except Exception as e:
            print(f"✗ 编辑器回调注销失败: {e}")