"""
网络同步插件
为EG引擎提供完整的网络同步功能
"""

from .core.sync_manager import SyncManager
from .network.network_manager import NetworkManager
from .protocol.protocol_handler import ProtocolHandler
from .sync.object_sync import ObjectSync
from .connection.connection_manager import ConnectionManager
from .serialization.data_serializer import DataSerializer
from .clock.clock_sync import ClockSync
from .prediction.prediction_manager import PredictionManager
from .config.sync_config import SyncConfig
from .editor.sync_editor import SyncEditor
from .events.event_handler import NetworkEventHandler
from .utils.network_utils import NetworkUtils
from .encryption.encryption_manager import EncryptionManager

class NetworkSyncPlugin:
    """
    网络同步插件主类
    整合所有网络同步功能模块
    """
    
    def __init__(self, engine):
        """
        初始化网络同步插件
        
        Args:
            engine: EG引擎实例
        """
        self.engine = engine
        self.name = "NetworkSync"
        self.version = "1.0.0"
        self.author = "EG Plugin System"
        
        # 功能模块
        self.sync_manager = None
        self.network_manager = None
        self.protocol_handler = None
        self.object_sync = None
        self.connection_manager = None
        self.data_serializer = None
        self.clock_sync = None
        self.prediction_manager = None
        self.sync_config = None
        self.sync_editor = None
        self.event_handler = None
        self.network_utils = None
        self.encryption_manager = None
        
        # 插件状态
        self.enabled = False
        self.initialized = False
        self.is_server = False
        self.is_client = False
        
        # 性能统计
        self.stats = {
            'bytes_sent': 0,
            'bytes_received': 0,
            'packets_sent': 0,
            'packets_received': 0,
            'sync_objects': 0,
            'connections': 0,
            'sync_errors': 0,
            'latency': 0.0
        }
        
        print(f"✓ 网络同步插件 v{self.version} 已创建")
        
    def initialize(self) -> bool:
        """
        初始化插件
        
        Returns:
            是否初始化成功
        """
        try:
            print("正在初始化网络同步插件...")
            
            # 初始化核心组件
            self.sync_manager = SyncManager(self)
            self.network_manager = NetworkManager(self)
            self.protocol_handler = ProtocolHandler(self)
            self.object_sync = ObjectSync(self)
            self.connection_manager = ConnectionManager(self)
            self.data_serializer = DataSerializer(self)
            self.clock_sync = ClockSync(self)
            self.prediction_manager = PredictionManager(self)
            self.sync_config = SyncConfig(self)
            self.sync_editor = SyncEditor(self)
            self.event_handler = NetworkEventHandler(self)
            self.network_utils = NetworkUtils(self)
            self.encryption_manager = EncryptionManager(self)
            
            # 初始化各个模块
            modules = [
                self.sync_manager,
                self.network_manager,
                self.protocol_handler,
                self.object_sync,
                self.connection_manager,
                self.data_serializer,
                self.clock_sync,
                self.prediction_manager,
                self.sync_config,
                self.sync_editor,
                self.event_handler,
                self.network_utils,
                self.encryption_manager
            ]
            
            for module in modules:
                if module and not module.initialize():
                    print(f"✗ 模块初始化失败: {module.__class__.__name__}")
                    return False
                    
            self.initialized = True
            print("✓ 网络同步插件初始化完成")
            return True
            
        except Exception as e:
            print(f"✗ 网络同步插件初始化失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def enable(self) -> bool:
        """
        启用插件
        
        Returns:
            是否启用成功
        """
        try:
            if not self.initialized:
                print("✗ 插件未初始化")
                return False
                
            print("正在启用网络同步插件...")
            
            # 启用各个模块
            modules = [
                self.sync_manager,
                self.network_manager,
                self.protocol_handler,
                self.object_sync,
                self.connection_manager,
                self.data_serializer,
                self.clock_sync,
                self.prediction_manager,
                self.sync_config,
                self.sync_editor,
                self.event_handler,
                self.network_utils,
                self.encryption_manager
            ]
            
            for module in modules:
                if module and not module.enable():
                    print(f"✗ 模块启用失败: {module.__class__.__name__}")
                    return False
                    
            self.enabled = True
            print("✓ 网络同步插件已启用")
            return True
            
        except Exception as e:
            print(f"✗ 网络同步插件启用失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def disable(self):
        """禁用插件"""
        try:
            if not self.enabled:
                return
                
            print("正在禁用网络同步插件...")
            
            # 禁用各个模块
            modules = [
                self.sync_manager,
                self.network_manager,
                self.protocol_handler,
                self.object_sync,
                self.connection_manager,
                self.data_serializer,
                self.clock_sync,
                self.prediction_manager,
                self.sync_config,
                self.sync_editor,
                self.event_handler,
                self.network_utils,
                self.encryption_manager
            ]
            
            for module in modules:
                if module:
                    module.disable()
                    
            self.enabled = False
            print("✓ 网络同步插件已禁用")
            
        except Exception as e:
            print(f"✗ 网络同步插件禁用失败: {e}")
            import traceback
            traceback.print_exc()
            
    def finalize(self):
        """清理插件资源"""
        try:
            print("正在清理网络同步插件资源...")
            
            # 清理各个模块
            modules = [
                self.sync_manager,
                self.network_manager,
                self.protocol_handler,
                self.object_sync,
                self.connection_manager,
                self.data_serializer,
                self.clock_sync,
                self.prediction_manager,
                self.sync_config,
                self.sync_editor,
                self.event_handler,
                self.network_utils,
                self.encryption_manager
            ]
            
            for module in modules:
                if module:
                    module.finalize()
                    
            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
                
            # 更新各个模块
            modules = [
                self.sync_manager,
                self.network_manager,
                self.protocol_handler,
                self.object_sync,
                self.connection_manager,
                self.data_serializer,
                self.clock_sync,
                self.prediction_manager,
                self.sync_config,
                self.sync_editor,
                self.event_handler,
                self.network_utils,
                self.encryption_manager
            ]
            
            for module in modules:
                if module:
                    module.update(dt)
                    
        except Exception as e:
            print(f"✗ 网络同步插件更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def start_server(self, port: int = 7777) -> bool:
        """
        启动服务器
        
        Args:
            port: 服务器端口
            
        Returns:
            是否启动成功
        """
        try:
            if not self.enabled:
                print("✗ 插件未启用")
                return False
                
            if self.network_manager.start_server(port):
                self.is_server = True
                self.is_client = False
                print(f"✓ 服务器已启动，端口: {port}")
                return True
            else:
                print("✗ 服务器启动失败")
                return False
                
        except Exception as e:
            print(f"✗ 服务器启动异常: {e}")
            return False
            
    def connect_to_server(self, host: str, port: int = 7777) -> bool:
        """
        连接到服务器
        
        Args:
            host: 服务器地址
            port: 服务器端口
            
        Returns:
            是否连接成功
        """
        try:
            if not self.enabled:
                print("✗ 插件未启用")
                return False
                
            if self.connection_manager.connect_to_server(host, port):
                self.is_client = True
                self.is_server = False
                print(f"✓ 已连接到服务器 {host}:{port}")
                return True
            else:
                print("✗ 连接服务器失败")
                return False
                
        except Exception as e:
            print(f"✗ 连接服务器异常: {e}")
            return False
            
    def disconnect(self):
        """断开连接"""
        try:
            if self.is_server:
                self.network_manager.stop_server()
                self.is_server = False
            elif self.is_client:
                self.connection_manager.disconnect()
                self.is_client = False
                
            print("✓ 已断开连接")
        except Exception as e:
            print(f"✗ 断开连接失败: {e}")
            
    def sync_object(self, obj_id: str, obj_data: dict) -> bool:
        """
        同步对象
        
        Args:
            obj_id: 对象ID
            obj_data: 对象数据
            
        Returns:
            是否同步成功
        """
        try:
            if not self.enabled:
                print("✗ 插件未启用")
                return False
                
            return self.object_sync.sync_object(obj_id, obj_data)
        except Exception as e:
            print(f"✗ 对象同步失败: {e}")
            return False
            
    def get_stats(self) -> dict:
        """
        获取插件统计信息
        
        Returns:
            统计信息字典
        """
        return self.stats.copy()
        
    def reset_stats(self):
        """重置统计信息"""
        self.stats = {
            'bytes_sent': 0,
            'bytes_received': 0,
            'packets_sent': 0,
            'packets_received': 0,
            'sync_objects': 0,
            'connections': 0,
            'sync_errors': 0,
            'latency': 0.0
        }
        print("✓ 网络同步统计信息已重置")