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

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

class CommEditor:
    """
    通信编辑器
    提供图形界面配置通信参数
    """
    
    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_client": None,
            "selected_room": 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": {},
            "client_data": {},
            "room_data": {},
            "message_stats": {},
            "network_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"},
                "clients": {"name": "客户端", "icon": "people"},
                "rooms": {"name": "房间", "icon": "meeting_room"},
                "messages": {"name": "消息", "icon": "message"},
                "network": {"name": "网络", "icon": "network"},
                "config": {"name": "配置", "icon": "settings"},
                "statistics": {"name": "统计", "icon": "bar_chart"}
            }
            
            # 创建面板
            self.ui_components["panels"] = {
                "server_status": {"title": "服务器状态", "visible": True},
                "performance": {"title": "性能指标", "visible": True},
                "clients_list": {"title": "客户端列表", "visible": True},
                "rooms_list": {"title": "房间列表", "visible": True},
                "message_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:
            # 更新服务器状态面板
            if self.plugin.websocket_server:
                server_stats = self.plugin.websocket_server.get_server_stats()
                self.ui_components["panels"]["server_status"]["data"] = server_stats
                
            # 更新客户端列表面板
            if self.plugin.client_manager:
                clients = self.plugin.client_manager.get_all_clients()
                self.ui_components["panels"]["clients_list"]["data"] = clients
                
            # 更新房间列表面板
            if self.plugin.room_manager:
                rooms = self.plugin.room_manager.get_all_rooms()
                self.ui_components["panels"]["rooms_list"]["data"] = rooms
                
            # 更新消息统计面板
            if self.plugin.message_router:
                message_stats = self.plugin.message_router.get_message_stats()
                self.ui_components["panels"]["message_stats"]["data"] = message_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.client_manager:
                clients = self.plugin.client_manager.get_all_clients()
                self.realtime_data["client_data"] = clients
                
            # 更新房间数据
            if self.plugin.room_manager:
                rooms = self.plugin.room_manager.get_all_rooms()
                self.realtime_data["room_data"] = rooms
                
            # 更新消息统计
            if self.plugin.message_router:
                message_stats = self.plugin.message_router.get_message_stats()
                self.realtime_data["message_stats"] = message_stats
                
            # 更新网络统计
            if self.plugin.websocket_server:
                network_stats = self.plugin.websocket_server.get_server_stats()
                self.realtime_data["network_stats"] = network_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_client(self, client_id: str):
        """
        选择客户端
        
        Args:
            client_id: 客户端ID
        """
        try:
            self.editor_state["selected_client"] = client_id
            print(f"✓ 选择客户端: {client_id}")
            
        except Exception as e:
            print(f"✗ 客户端选择失败: {e}")
            self.editor_stats["editor_errors"] += 1
            
    def select_room(self, room_id: str):
        """
        选择房间
        
        Args:
            room_id: 房间ID
        """
        try:
            self.editor_state["selected_room"] = room_id
            print(f"✓ 选择房间: {room_id}")
            
        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 == "clients":
                export_data = self.realtime_data["client_data"]
            elif data_type == "rooms":
                export_data = self.realtime_data["room_data"]
            elif data_type == "messages":
                export_data = self.realtime_data["message_stats"]
            elif data_type == "network":
                export_data = self.realtime_data["network_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}")