"""
天气编辑器
提供可视化界面用于编辑和调整天气和季节参数
"""

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

class WeatherEditor:
    """
    天气编辑器
    提供可视化界面用于编辑和调整天气和季节参数，包括实时预览、参数调整等功能
    """
    
    def __init__(self, plugin):
        """
        初始化天气编辑器
        
        Args:
            plugin: 天气和季节系统插件实例
        """
        self.plugin = plugin
        self.enabled = False
        self.initialized = False
        
        # 编辑器配置
        self.editor_config = {
            'auto_preview': True,
            'realtime_update': True,
            'preview_quality': 'medium',
            'history_limit': 50
        }
        
        # 编辑模式
        self.edit_modes = {
            'weather': {'name': '天气编辑', 'description': '编辑天气参数'},
            'season': {'name': '季节编辑', 'description': '编辑季节参数'},
            'environment': {'name': '环境编辑', 'description': '编辑环境效果参数'},
            'particles': {'name': '粒子编辑', 'description': '编辑粒子效果参数'},
            'audio': {'name': '音频编辑', 'description': '编辑音频效果参数'}
        }
        
        self.current_edit_mode = 'weather'
        
        # 参数分组
        self.parameter_groups = {
            'weather': ['temperature', 'humidity', 'wind_speed', 'precipitation', 'visibility'],
            'season': ['season_progress', 'day_length', 'temperature_range', 'vegetation_growth'],
            'environment': ['light_intensity', 'fog_density', 'wind_turbulence'],
            'particles': ['particle_count', 'particle_size', 'emission_rate'],
            'audio': ['master_volume', 'effects_volume', 'ambient_volume']
        }
        
        # 编辑历史
        self.edit_history = []
        self.history_position = -1
        
        # 预览数据
        self.preview_data = None
        self.preview_dirty = False
        
        # 工具状态
        self.is_editing = False
        self.selected_parameter = None
        
        # 统计信息
        self.stats = {
            'edits_made': 0,
            'undos_performed': 0,
            'redos_performed': 0,
            'total_edit_time': 0.0,
            'average_edit_time': 0.0
        }
        
        # UI组件引用（在实际实现中会连接到GUI）
        self.ui_components = {
            'toolbar': None,
            'properties_panel': None,
            'preview_window': None,
            'parameter_sliders': None,
            'history_panel': None
        }
        
        print("✓ 天气编辑器已创建")
        
    def initialize(self) -> bool:
        """
        初始化天气编辑器
        
        Returns:
            是否初始化成功
        """
        try:
            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
                
            self.enabled = True
            print("✓ 天气编辑器已启用")
            return True
            
        except Exception as e:
            print(f"✗ 天气编辑器启用失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def disable(self):
        """禁用天气编辑器"""
        try:
            self.enabled = False
            print("✓ 天气编辑器已禁用")
            
        except Exception as e:
            print(f"✗ 天气编辑器禁用失败: {e}")
            import traceback
            traceback.print_exc()
            
    def finalize(self):
        """清理天气编辑器资源"""
        try:
            self.disable()
            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
                
            # 更新预览
            if self.preview_dirty and self.editor_config['auto_preview']:
                self._update_preview()
                
            # 处理实时更新
            if self.editor_config['realtime_update']:
                self._handle_realtime_updates()
                
        except Exception as e:
            print(f"✗ 天气编辑器更新失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _update_preview(self):
        """更新预览显示"""
        try:
            # 在实际实现中，这里会更新预览窗口
            self.preview_dirty = False
        except Exception as e:
            print(f"✗ 预览更新失败: {e}")
            
    def _handle_realtime_updates(self):
        """处理实时更新"""
        try:
            # 在实际实现中，这里会处理实时编辑更新
            pass
        except Exception as e:
            print(f"✗ 实时更新处理失败: {e}")
            
    def set_edit_mode(self, mode: str):
        """
        设置编辑模式
        
        Args:
            mode: 编辑模式
        """
        if mode in self.edit_modes:
            self.current_edit_mode = mode
            print(f"✓ 编辑模式设置为: {self.edit_modes[mode]['name']}")
        else:
            print(f"✗ 无效的编辑模式: {mode}")
            
    def get_edit_modes(self) -> Dict[str, Dict[str, str]]:
        """
        获取可用的编辑模式
        
        Returns:
            编辑模式字典
        """
        return self.edit_modes.copy()
        
    def get_current_edit_mode(self) -> str:
        """
        获取当前编辑模式
        
        Returns:
            当前编辑模式
        """
        return self.current_edit_mode
        
    def set_parameter(self, parameter_name: str, value: Any):
        """
        设置参数值
        
        Args:
            parameter_name: 参数名称
            value: 参数值
        """
        try:
            # 保存当前状态到历史记录
            self._save_state_to_history()
            
            # 根据编辑模式应用参数
            if self.current_edit_mode == 'weather' and self.plugin.weather_manager:
                # 处理天气参数
                if parameter_name == 'temperature':
                    self.plugin.weather_manager.set_base_temperature(value)
                elif parameter_name == 'humidity':
                    self.plugin.weather_manager.set_base_humidity(value)
                elif parameter_name == 'wind_speed':
                    self.plugin.weather_manager.set_base_wind_speed(value)
                elif parameter_name == 'visibility':
                    # 在实际实现中会调用相应方法
                    pass
                    
            elif self.current_edit_mode == 'season' and self.plugin.season_manager:
                # 处理季节参数
                if parameter_name == 'season_progress':
                    # 在实际实现中会调用相应方法
                    pass
                    
            elif self.current_edit_mode == 'environment' and self.plugin.environment_effects:
                # 处理环境参数
                self.plugin.environment_effects.set_effect_parameter('lighting', parameter_name, value)
                
            elif self.current_edit_mode == 'particles' and self.plugin.particle_effects:
                # 处理粒子参数
                # 在实际实现中会调用相应方法
                pass
                
            elif self.current_edit_mode == 'audio' and self.plugin.audio_manager:
                # 处理音频参数
                self.plugin.audio_manager.set_audio_parameter(parameter_name, value)
                
            # 标记预览需要更新
            self.preview_dirty = True
            
            # 更新统计信息
            self.stats['edits_made'] += 1
            
            print(f"✓ 参数 '{parameter_name}' 设置为: {value}")
            
        except Exception as e:
            print(f"✗ 参数设置失败: {e}")
            import traceback
            traceback.print_exc()
            
    def get_parameter(self, parameter_name: str) -> Any:
        """
        获取参数值
        
        Args:
            parameter_name: 参数名称
            
        Returns:
            参数值
        """
        try:
            # 根据编辑模式获取参数
            if self.current_edit_mode == 'weather' and self.plugin.weather_manager:
                env_params = self.plugin.weather_manager.get_current_environment_params()
                return env_params.get(parameter_name)
                
            elif self.current_edit_mode == 'season' and self.plugin.season_manager:
                # 在实际实现中会获取相应参数
                pass
                
            elif self.current_edit_mode == 'environment' and self.plugin.environment_effects:
                effects = self.plugin.environment_effects.get_current_effects()
                # 简化实现，实际中需要更复杂的逻辑
                for effect_type, params in effects.items():
                    if parameter_name in params:
                        return params[parameter_name]
                        
            elif self.current_edit_mode == 'particles' and self.plugin.particle_effects:
                # 在实际实现中会获取相应参数
                pass
                
            elif self.current_edit_mode == 'audio' and self.plugin.audio_manager:
                audio_params = self.plugin.audio_manager.get_audio_parameters()
                return audio_params.get(parameter_name)
                
        except Exception as e:
            print(f"✗ 参数获取失败: {e}")
            import traceback
            traceback.print_exc()
            
        return None
        
    def _save_state_to_history(self):
        """保存当前状态到历史记录"""
        try:
            # 创建状态快照
            state_snapshot = {
                'timestamp': time.time(),
                'edit_mode': self.current_edit_mode,
                'weather_params': {},
                'season_params': {},
                'environment_params': {},
                'audio_params': {}
            }
            
            # 保存天气参数
            if self.plugin.weather_manager:
                state_snapshot['weather_params'] = self.plugin.weather_manager.get_current_environment_params()
                
            # 保存季节参数
            if self.plugin.season_manager:
                state_snapshot['season_params'] = self.plugin.season_manager.get_interpolated_season_params()
                
            # 保存环境参数
            if self.plugin.environment_effects:
                state_snapshot['environment_params'] = self.plugin.environment_effects.get_current_effects()
                
            # 保存音频参数
            if self.plugin.audio_manager:
                state_snapshot['audio_params'] = self.plugin.audio_manager.get_audio_parameters()
                
            # 添加到历史记录
            if self.history_position < len(self.edit_history) - 1:
                # 如果当前不在历史记录末尾，截断后续记录
                self.edit_history = self.edit_history[:self.history_position + 1]
                
            self.edit_history.append(state_snapshot)
            self.history_position += 1
            
            # 限制历史记录数量
            if len(self.edit_history) > self.editor_config['history_limit']:
                self.edit_history.pop(0)
                self.history_position -= 1
                
        except Exception as e:
            print(f"✗ 状态保存失败: {e}")
            import traceback
            traceback.print_exc()
            
    def undo(self) -> bool:
        """
        撤销操作
        
        Returns:
            是否撤销成功
        """
        try:
            if not self.enabled:
                print("✗ 天气编辑器未启用")
                return False
                
            if self.history_position <= 0:
                print("✗ 没有可撤销的操作")
                return False
                
            # 移动到前一个历史状态
            self.history_position -= 1
            
            # 恢复状态
            self._restore_state_from_history()
            
            # 更新统计信息
            self.stats['undos_performed'] += 1
            
            print("✓ 撤销操作完成")
            return True
            
        except Exception as e:
            print(f"✗ 撤销操作失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def redo(self) -> bool:
        """
        重做操作
        
        Returns:
            是否重做成功
        """
        try:
            if not self.enabled:
                print("✗ 天气编辑器未启用")
                return False
                
            if self.history_position >= len(self.edit_history) - 1:
                print("✗ 没有可重做的操作")
                return False
                
            # 移动到下一个历史状态
            self.history_position += 1
            
            # 恢复状态
            self._restore_state_from_history()
            
            # 更新统计信息
            self.stats['redos_performed'] += 1
            
            print("✓ 重做操作完成")
            return True
            
        except Exception as e:
            print(f"✗ 重做操作失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def _restore_state_from_history(self):
        """从历史记录恢复状态"""
        try:
            if self.history_position < 0:
                return
                
            # 获取历史状态
            state = self.edit_history[self.history_position]
            
            # 恢复参数
            if self.plugin.weather_manager and state['weather_params']:
                # 恢复天气参数
                weather_params = state['weather_params']
                if 'temperature' in weather_params:
                    self.plugin.weather_manager.set_base_temperature(weather_params['temperature'])
                if 'humidity' in weather_params:
                    self.plugin.weather_manager.set_base_humidity(weather_params['humidity'])
                if 'wind_speed' in weather_params:
                    self.plugin.weather_manager.set_base_wind_speed(weather_params['wind_speed'])
                    
            if self.plugin.audio_manager and state['audio_params']:
                # 恢复音频参数
                audio_params = state['audio_params']
                for param_name, param_value in audio_params.items():
                    self.plugin.audio_manager.set_audio_parameter(param_name, param_value)
                    
            # 标记预览需要更新
            self.preview_dirty = True
            
        except Exception as e:
            print(f"✗ 状态恢复失败: {e}")
            import traceback
            traceback.print_exc()
            
    def clear_history(self):
        """清空历史记录"""
        try:
            self.edit_history.clear()
            self.history_position = -1
            print("✓ 历史记录已清空")
        except Exception as e:
            print(f"✗ 历史记录清空失败: {e}")
            import traceback
            traceback.print_exc()
            
    def get_parameter_groups(self) -> Dict[str, List[str]]:
        """
        获取参数分组
        
        Returns:
            参数分组字典
        """
        return self.parameter_groups.copy()
        
    def get_parameters_in_group(self, group_name: str) -> List[str]:
        """
        获取组中的参数列表
        
        Args:
            group_name: 组名称
            
        Returns:
            参数列表
        """
        return self.parameter_groups.get(group_name, []).copy()
        
    def set_editor_config(self, config: Dict[str, Any]):
        """
        设置编辑器配置
        
        Args:
            config: 配置字典
        """
        self.editor_config.update(config)
        print(f"✓ 编辑器配置已更新: {self.editor_config}")
        
    def get_editor_config(self) -> Dict[str, Any]:
        """
        获取编辑器配置
        
        Returns:
            配置字典
        """
        return self.editor_config.copy()
        
    def get_stats(self) -> Dict[str, Any]:
        """
        获取统计信息
        
        Returns:
            统计信息字典
        """
        # 更新平均编辑时间
        total_edits = self.stats['edits_made'] + self.stats['undos_performed'] + self.stats['redos_performed']
        if total_edits > 0:
            self.stats['average_edit_time'] = self.stats['total_edit_time'] / total_edits
        return self.stats.copy()
        
    def reset_stats(self):
        """重置统计信息"""
        self.stats = {
            'edits_made': 0,
            'undos_performed': 0,
            'redos_performed': 0,
            'total_edit_time': 0.0,
            'average_edit_time': 0.0
        }
        print("✓ 天气编辑器统计信息已重置")
        
    def export_editor_state(self, filename: str) -> bool:
        """
        导出编辑器状态
        
        Args:
            filename: 文件名
            
        Returns:
            是否导出成功
        """
        try:
            # 创建状态数据
            state_data = {
                'editor_config': self.editor_config,
                'current_edit_mode': self.current_edit_mode,
                'parameter_groups': self.parameter_groups,
                'timestamp': time.time()
            }
            
            # 保存为JSON文件
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(state_data, f, ensure_ascii=False, indent=2)
                
            print(f"✓ 编辑器状态已导出到: {filename}")
            return True
            
        except Exception as e:
            print(f"✗ 编辑器状态导出失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def import_editor_state(self, filename: str) -> bool:
        """
        导入编辑器状态
        
        Args:
            filename: 文件名
            
        Returns:
            是否导入成功
        """
        try:
            # 读取JSON文件
            with open(filename, 'r', encoding='utf-8') as f:
                state_data = json.load(f)
                
            # 应用状态
            if 'editor_config' in state_data:
                self.set_editor_config(state_data['editor_config'])
            if 'current_edit_mode' in state_data:
                self.set_edit_mode(state_data['current_edit_mode'])
                
            print(f"✓ 编辑器状态已从 {filename} 导入")
            return True
            
        except Exception as e:
            print(f"✗ 编辑器状态导入失败: {e}")
            import traceback
            traceback.print_exc()
            return False
            
    def set_ui_component(self, component_name: str, component: Any):
        """
        设置UI组件引用
        
        Args:
            component_name: 组件名称
            component: 组件引用
        """
        if component_name in self.ui_components:
            self.ui_components[component_name] = component
            print(f"✓ UI组件 '{component_name}' 已设置")
        else:
            print(f"✗ 无效的UI组件名称: {component_name}")
            
    def refresh_ui(self):
        """刷新UI显示"""
        try:
            # 在实际实现中，这里会更新所有UI组件的显示
            print("✓ UI刷新完成")
        except Exception as e:
            print(f"✗ UI刷新失败: {e}")
            
    def show_preview_window(self):
        """显示预览窗口"""
        try:
            # 在实际实现中，这里会创建并显示预览窗口
            print("✓ 预览窗口已显示")
        except Exception as e:
            print(f"✗ 预览窗口显示失败: {e}")
            
    def hide_preview_window(self):
        """隐藏预览窗口"""
        try:
            # 在实际实现中，这里会隐藏预览窗口
            print("✓ 预览窗口已隐藏")
        except Exception as e:
            print(f"✗ 预览窗口隐藏失败: {e}")
            
    def update_preview_window(self):
        """更新预览窗口内容"""
        try:
            # 在实际实现中，这里会更新预览窗口的内容
            print("✓ 预览窗口已更新")
        except Exception as e:
            print(f"✗ 预览窗口更新失败: {e}")
            
    def apply_preset(self, preset_name: str):
        """
        应用预设
        
        Args:
            preset_name: 预设名称
        """
        try:
            if self.plugin.preset_manager:
                self.plugin.preset_manager.apply_preset(preset_name)
                self.preview_dirty = True
                print(f"✓ 预设 '{preset_name}' 已应用")
            else:
                print("✗ 预设管理器不可用")
        except Exception as e:
            print(f"✗ 预设应用失败: {e}")
            import traceback
            traceback.print_exc()
            
    def save_current_as_preset(self, preset_name: str, description: str = '') -> str:
        """
        将当前配置保存为预设
        
        Args:
            preset_name: 预设名称
            description: 预设描述
            
        Returns:
            预设ID
        """
        try:
            if self.plugin.preset_manager:
                preset_id = self.plugin.preset_manager.create_terrain_preset_from_current(preset_name, description)
                print(f"✓ 当前配置已保存为预设: {preset_name}")
                return preset_id
            else:
                print("✗ 预设管理器不可用")
                return ''
        except Exception as e:
            print(f"✗ 预设保存失败: {e}")
            import traceback
            traceback.print_exc()
            return ''