"""
Morphing和变形动画插件
完整的顶点变形、morphing目标、网格变形解决方案
"""

from plugins.plugin_manager import BasePlugin
from direct.showbase.DirectObject import DirectObject

# 导入核心模块
from .core import MorphingCore
from .advanced import AnimationStateMachine, AnimationCurveEditor, PhysicsAnimationIntegration
from .optimization import AnimationCompressor, AnimationLODSystem, AnimationCacheManager
from .network import AnimationNetworkSync
from .tools import AnimationAnalyzer, AnimationEditor, DebugVisualizer, AnimationProfiler

class MorphingAnimationPlugin(BasePlugin):
    """
    Morphing和变形动画插件
    提供完整的顶点变形、morphing目标、网格变形等高级动画功能
    """
    
    def __init__(self, plugin_manager, name):
        """
        初始化Morphing动画插件
        :param plugin_manager: 插件管理器
        :param name: 插件名称
        """
        super().__init__(plugin_manager, name)
        self.config = {
            "version": "1.0.0",
            "author": "Morphing Animation Team",
            "description": "完整的顶点变形、morphing目标、网格变形解决方案"
        }
        
        # 核心系统组件
        self.core_system = None
        self.state_machine_system = None
        self.curve_editor_system = None
        self.physics_integration_system = None
        self.compressor_system = None
        self.lod_system = None
        self.cache_manager_system = None
        self.network_system = None
        
        # 工具系统组件
        self.analyzer_system = None
        self.editor_system = None
        self.visualizer_system = None
        self.profiler_system = None
        
        self.is_enabled = False
        self.update_task = None
        
        print(f"Morphing动画插件初始化: {self.name}")
        
    def initialize(self) -> bool:
        """
        初始化插件
        :return: 是否初始化成功
        """
        try:
            world = self.plugin_manager.world
            
            # 创建核心系统
            self.core_system = MorphingCore(world)
            
            # 创建高级功能系统
            self.curve_editor_system = AnimationCurveEditor(self.core_system)
            self.physics_integration_system = PhysicsAnimationIntegration(self.core_system)
            
            # 创建优化系统
            self.compressor_system = AnimationCompressor()
            self.lod_system = AnimationLODSystem(world)
            self.cache_manager_system = AnimationCacheManager()
            
            # 创建网络同步系统
            self.network_system = AnimationNetworkSync(world, self.core_system)
            
            # 创建工具系统
            self.analyzer_system = AnimationAnalyzer(self.core_system)
            self.editor_system = AnimationEditor(self.core_system, self.curve_editor_system)
            self.visualizer_system = DebugVisualizer(world, self.core_system)
            self.profiler_system = AnimationProfiler(world, self.core_system)
            
            print(f"Morphing动画插件初始化成功: {self.name}")
            return True
            
        except Exception as e:
            print(f"Morphing动画插件初始化失败: {e}")
            import traceback
            traceback.print_exc()
            return False
        
    def enable(self) -> bool:
        """
        启用插件
        :return: 是否启用成功
        """
        if not super().enable():
            return False
            
        if self.is_enabled:
            print(f"Morphing动画插件已启用: {self.name}")
            return True
            
        try:
            # 启动核心系统更新
            self.core_system.start_updating()
            
            # 启动曲线编辑器更新
            self.curve_editor_system.start_updating()
            
            # 启动物理集成系统更新
            self.physics_integration_system.start_updating()
            
            # 启动网络同步
            self.network_system.start_sync_task()
            
            # 启动工具系统更新
            self.visualizer_system.is_visualizing = True
            self.profiler_system.is_profiling = True
            
            # 启动更新任务
            self.update_task = self.plugin_manager.world.taskMgr.add(
                self._update_task, 
                f"morphing_animation_update_{self.name}",
                sort=35
            )
            
            # 标记为已启用
            self.is_enabled = True
            
            print(f"Morphing动画插件启用成功: {self.name}")
            return True
            
        except Exception as e:
            print(f"Morphing动画插件启用失败: {e}")
            import traceback
            traceback.print_exc()
            return False
        
    def disable(self) -> bool:
        """
        禁用插件
        :return: 是否禁用成功
        """
        if not super().disable():
            return False
            
        if self.is_enabled:
            print(f"Morphing动画插件已禁用: {self.name}")
            return True
            
        try:
            # 停止更新任务
            if self.update_task:
                self.plugin_manager.world.taskMgr.remove(self.update_task)
                self.update_task = None
                
            # 停止核心系统更新
            self.core_system.stop_updating()
            
            # 停止曲线编辑器更新
            self.curve_editor_system.stop_updating()
            
            # 停止物理集成系统更新
            self.physics_integration_system.stop_updating()
            
            # 停止网络同步
            self.network_system.stop_sync_task()
            
            # 停止工具系统更新
            self.visualizer_system.is_visualizing = False
            self.profiler_system.is_profiling = False
            
            # 标记为已禁用
            self.is_enabled = False
            
            print(f"Morphing动画插件禁用成功: {self.name}")
            return True
            
        except Exception as e:
            print(f"Morphing动画插件禁用失败: {e}")
            import traceback
            traceback.print_exc()
            return False
        
    def finalize(self) -> None:
        """
        清理插件资源
        """
        print(f"清理Morphing动画插件资源: {self.name}")
        
        try:
            # 停止更新任务
            if self.update_task:
                self.plugin_manager.world.taskMgr.remove(self.update_task)
                self.update_task = None
                
            # 停止所有系统
            if self.core_system:
                self.core_system.stop_updating()
            if self.curve_editor_system:
                self.curve_editor_system.stop_updating()
            if self.physics_integration_system:
                self.physics_integration_system.stop_updating()
            if self.network_system:
                self.network_system.stop_sync_task()
            if self.visualizer_system:
                self.visualizer_system.is_visualizing = False
            if self.profiler_system:
                self.profiler_system.is_profiling = False
                
            # 清理资源
            self.core_system = None
            self.state_machine_system = None
            self.curve_editor_system = None
            self.physics_integration_system = None
            self.compressor_system = None
            self.lod_system = None
            self.cache_manager_system = None
            self.network_system = None
            self.analyzer_system = None
            self.editor_system = None
            self.visualizer_system = None
            self.profiler_system = None
            
            print(f"Morphing动画插件资源清理完成: {self.name}")
            
        except Exception as e:
            print(f"清理Morphing动画插件资源失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _update_task(self, task) -> int:
        """
        插件更新任务
        :param task: 任务对象
        :return: 任务状态
        """
        try:
            dt = globalClock.getDt()
            
            # 更新核心系统
            if self.core_system:
                self.core_system.update(dt)
                
            # 更新高级功能系统
            if self.curve_editor_system:
                self.curve_editor_system.update(dt)
                
            # 更新物理集成系统
            if self.physics_integration_system:
                self.physics_integration_system.update(dt)
                
            # 更新LOD系统
            if self.lod_system and self.core_system:
                self.lod_system.update_lod_levels(self.core_system.model_data)
                
            # 更新工具系统
            if self.visualizer_system:
                self.visualizer_system.update(dt)
                
            if self.profiler_system:
                self.profiler_system.sample_performance(dt)
                
        except Exception as e:
            print(f"插件更新任务出错: {e}")
            
        return task.cont
            
    # 核心系统访问方法
    def get_core_system(self):
        """
        获取核心动画系统
        :return: MorphingCore实例
        """
        return self.core_system
        
    def get_state_machine_system(self, model_id: str):
        """
        获取动画状态机系统
        :param model_id: 模型ID
        :return: AnimationStateMachine实例
        """
        if self.core_system:
            if not self.state_machine_system:
                self.state_machine_system = {}
            if model_id not in self.state_machine_system:
                self.state_machine_system[model_id] = AnimationStateMachine(self.core_system, model_id)
            return self.state_machine_system[model_id]
        return None
        
    def get_curve_editor_system(self):
        """
        获取曲线编辑器系统
        :return: AnimationCurveEditor实例
        """
        return self.curve_editor_system
        
    def get_physics_integration_system(self):
        """
        获取物理集成系统
        :return: PhysicsAnimationIntegration实例
        """
        return self.physics_integration_system
        
    def get_compressor_system(self):
        """
        获取压缩系统
        :return: AnimationCompressor实例
        """
        return self.compressor_system
        
    def get_lod_system(self):
        """
        获取LOD系统
        :return: AnimationLODSystem实例
        """
        return self.lod_system
        
    def get_cache_manager_system(self):
        """
        获取缓存管理系统
        :return: AnimationCacheManager实例
        """
        return self.cache_manager_system
        
    def get_network_system(self):
        """
        获取网络同步系统
        :return: AnimationNetworkSync实例
        """
        return self.network_system
        
    # 工具系统访问方法
    def get_analyzer_system(self):
        """
        获取动画分析器系统
        :return: AnimationAnalyzer实例
        """
        return self.analyzer_system
        
    def get_editor_system(self):
        """
        获取动画编辑器系统
        :return: AnimationEditor实例
        """
        return self.editor_system
        
    def get_visualizer_system(self):
        """
        获取调试可视化工具系统
        :return: DebugVisualizer实例
        """
        return self.visualizer_system
        
    def get_profiler_system(self):
        """
        获取动画性能分析器系统
        :return: AnimationProfiler实例
        """
        return self.profiler_system

# 兼容性接口
Plugin = MorphingAnimationPlugin

__all__ = [
    'MorphingAnimationPlugin',
    'Plugin',
    'MorphingCore',
    'AnimationStateMachine',
    'AnimationCurveEditor',
    'PhysicsAnimationIntegration',
    'AnimationCompressor',
    'AnimationLODSystem',
    'AnimationCacheManager',
    'AnimationNetworkSync',
    'AnimationAnalyzer',
    'AnimationEditor',
    'DebugVisualizer',
    'AnimationProfiler'
]