import random
import json
import ttkbootstrap as ttk
from src.utils.database import db_instance

# 读取配置
with open("config/settings.json", "r", encoding="utf-8") as f:
    CONFIG = json.load(f)
ANIM_CONFIG = CONFIG["animation"]

class AnimationEngine:
    """点名动画引擎（名字滚动、闪烁）"""
    def __init__(self, label: ttk.Label):
        self.label = label  # 展示动画的标签
        self.students = []
        self.is_running = False
        self.roll_count = 0

    def refresh_students(self):
        """刷新学生列表"""
        self.students = db_instance.get_all_students()

    def _roll_name(self, final_student: tuple = None):
        """名字滚动动画"""
        if not self.students:
            self.label.config(text="暂无学生数据")
            return
        
        if self.roll_count >= ANIM_CONFIG["roll_times"] and final_student:
            # 动画结束，显示最终结果
            self.is_running = False
            self.label.config(
                text=f"🎉 点名结果 🎉\n学号：{final_student[0]}\n姓名：{final_student[1]}\n专业：{final_student[2]}",
                font=("微软雅黑", 16, "bold")
            )
            # 闪烁效果
            self._flash_label()
            return

        # 随机显示学生名字（滚动）
        random_student = random.choice(self.students)
        self.label.config(
            text=f"正在随机点名...\n{random_student[1]}",
            font=("微软雅黑", 14)
        )
        self.roll_count += 1
        # 递归调用，实现滚动
        self.label.after(ANIM_CONFIG["roll_speed"], self._roll_name, final_student)

    def _flash_label(self):
        """标签闪烁效果"""
        current_color = self.label.cget("foreground")
        new_color = "red" if current_color != "red" else "black"
        self.label.config(foreground=new_color)
        # 持续闪烁1秒
        self.label.after(ANIM_CONFIG["flash_duration"], lambda: self.label.config(foreground="black"))

    def start_roll(self, final_student: tuple):
        """启动滚动动画"""
        self.is_running = True
        self.roll_count = 0
        self.refresh_students()
        self._roll_name(final_student)

# 示例：创建动画引擎时传入ttk.Label对象
# label = ttk.Label(text="测试")
# anim_engine = AnimationEngine(label)