#!/usr/bin/env python3
"""
动态字幕 UI 控制器 - 比格熊插件
提供 Text+ 属性设置界面和实时预览功能
"""
import sys
import os
import json
from typing import Dict, Any, Callable

# 添加模块路径
modules_dir = os.path.join(os.path.dirname(__file__), '..')
if modules_dir not in sys.path:
    sys.path.insert(0, modules_dir)

from modules.dynamic_subtitle import DynamicSubtitleModule

class DynamicSubtitleUI:
    """动态字幕 UI 控制器"""
    
    def __init__(self):
        self.module = DynamicSubtitleModule()
        self.ui_callbacks = {}
        self.current_subtitle_content = ""
        
    def register_callback(self, event_name: str, callback: Callable):
        """注册 UI 回调函数"""
        self.ui_callbacks[event_name] = callback
    
    def trigger_callback(self, event_name: str, *args, **kwargs):
        """触发 UI 回调"""
        if event_name in self.ui_callbacks:
            return self.ui_callbacks[event_name](*args, **kwargs)
        return None
    
    def update_text_settings(self, settings: Dict[str, Any]):
        """更新文本设置"""
        self.module.update_settings(settings)
        
        # 触发预览更新
        self.trigger_callback('preview_update', 
                           self.module.sample_text, 
                           self.module.current_settings.copy())
    
    def set_sample_text(self, text: str):
        """设置示例文本"""
        self.module.sample_text = text
        self.trigger_callback('preview_update', 
                           text, 
                           self.module.current_settings.copy())
    
    def start_preview(self):
        """启动实时预览"""
        def preview_callback(text, settings):
            self.trigger_callback('preview_update', text, settings)
        
        self.module.start_preview(preview_callback)
    
    def stop_preview(self):
        """停止实时预览"""
        self.module.stop_preview()
    
    def apply_to_timeline(self, subtitle_content: str = None):
        """应用到时间线"""
        content = subtitle_content or self.current_subtitle_content
        if not content:
            return {"success": False, "message": "没有字幕内容"}
        
        success = self.module.apply_to_timeline(content)
        if success:
            return {"success": True, "message": "字幕已成功添加到时间线"}
        else:
            return {"success": False, "message": "添加字幕到时间线失败"}
    
    def save_to_cache(self, subtitle_content: str, cache_dir: str):
        """保存到缓存"""
        self.current_subtitle_content = subtitle_content
        return self.module.save_to_cache(subtitle_content, cache_dir)
    
    def get_current_settings(self) -> Dict[str, Any]:
        """获取当前设置"""
        return self.module.current_settings.copy()
    
    def get_sample_text(self) -> str:
        """获取示例文本"""
        return self.module.sample_text

def create_dynamic_subtitle_handler():
    """创建动态字幕处理函数"""
    ui_controller = DynamicSubtitleUI()
    
    def handler(operation: str, *args):
        try:
            if operation == "start_preview":
                ui_controller.start_preview()
                return {"success": True, "message": "预览已启动"}
            
            elif operation == "stop_preview":
                ui_controller.stop_preview()
                return {"success": True, "message": "预览已停止"}
            
            elif operation == "update_settings":
                if len(args) == 0:
                    return {"success": False, "message": "缺少设置参数"}
                settings = json.loads(args[0])
                ui_controller.update_text_settings(settings)
                return {"success": True, "message": "设置已更新"}
            
            elif operation == "set_sample_text":
                if len(args) == 0:
                    return {"success": False, "message": "缺少文本参数"}
                ui_controller.set_sample_text(args[0])
                return {"success": True, "message": "示例文本已更新"}
            
            elif operation == "apply_to_timeline":
                subtitle_content = args[0] if len(args) > 0 else ""
                result = ui_controller.apply_to_timeline(subtitle_content)
                return result
            
            elif operation == "save_to_cache":
                if len(args) < 2:
                    return {"success": False, "message": "缺少字幕内容或缓存目录"}
                subtitle_content = args[0]
                cache_dir = args[1]
                success = ui_controller.save_to_cache(subtitle_content, cache_dir)
                if success:
                    return {"success": True, "message": "已保存到缓存"}
                else:
                    return {"success": False, "message": "保存缓存失败"}
            
            elif operation == "get_current_settings":
                settings = ui_controller.get_current_settings()
                return {"success": True, "data": settings}
            
            elif operation == "get_sample_text":
                text = ui_controller.get_sample_text()
                return {"success": True, "data": {"text": text}}
            
            else:
                return {"success": False, "message": f"未知操作: {operation}"}
        
        except Exception as e:
            import traceback
            return {
                "success": False,
                "message": str(e),
                "traceback": traceback.format_exc()
            }
    
    return handler