"""面板管理器（Step 6 重构）。

register_panel / show_panel / hide_all_panels —— 在右侧栏不同浮动面板间切换。
"""

import tkinter as tk

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from pqAutomationApp import PQAutomationApp


def register_panel(self: "PQAutomationApp", panel_name, frame, button, visible_attr):
    """注册一个面板到管理系统"""
    self.panels[panel_name] = {
        "frame": frame,
        "button": button,
        "visible_attr": visible_attr,
    }


def show_panel(self: "PQAutomationApp", panel_name):
    """显示指定面板，隐藏其他所有面板"""
    if panel_name not in self.panels:
        return

    # 如果当前面板就是要显示的面板，则隐藏它
    if self.current_panel == panel_name:
        self.hide_all_panels()
        return

    # 隐藏所有面板
    self.hide_all_panels()

    # 显示指定面板
    panel_info = self.panels[panel_name]

    # 隐藏主内容区域。
    # Local Dimming 作为并列测试类型时，需要保留顶部配置区，
    # 让用户在面板上方直接看到并修改配置项。
    if panel_name == "local_dimming":
        # 重新按“自适应高度”布局顶部配置区，避免其占用可扩展空间把
        # Local Dimming 主面板整体向下挤出大块空白。
        self.control_frame_top.pack_forget()
        self.control_frame_top.pack(
            side=tk.TOP, fill=tk.X, expand=False, padx=0, pady=5
        )
        self.control_frame_middle.pack_forget()
        self.control_frame_bottom.pack_forget()
    else:
        self.control_frame_top.pack_forget()
        self.control_frame_middle.pack_forget()
        self.control_frame_bottom.pack_forget()

    # 显示目标面板
    panel_info["frame"].pack(side=tk.TOP, fill=tk.BOTH, expand=True, padx=5, pady=5)

    # 更新按钮样式
    if panel_info["button"]:
        panel_info["button"].configure(style="SidebarSelected.TButton")

    # 更新状态
    setattr(self, panel_info["visible_attr"], True)
    self.current_panel = panel_name


def hide_all_panels(self: "PQAutomationApp"):
    """隐藏所有面板，显示主内容区域"""
    # 隐藏所有注册的面板
    for panel_name, panel_info in self.panels.items():
        panel_info["frame"].pack_forget()
        if panel_info["button"]:
            panel_info["button"].configure(style="Sidebar.TButton")
        setattr(self, panel_info["visible_attr"], False)

    # 显示主内容区域
    self.control_frame_top.pack(
        side=tk.TOP, fill=tk.BOTH, expand=True, padx=0, pady=5
    )
    self.control_frame_middle.pack(
        side=tk.TOP, fill=tk.BOTH, expand=True, padx=0, pady=5
    )
    self.control_frame_bottom.pack(
        side=tk.TOP, fill=tk.BOTH, expand=True, padx=0, pady=5
    )

    self.current_panel = None




class PanelManagerMixin:
    """由 tools/refactor_to_mixins.py 自动生成。
    把本模块的自由函数挂到 PQAutomationApp 上，便于 F12 跳转与类型推断。
    """
    register_panel = register_panel
    show_panel = show_panel
    hide_all_panels = hide_all_panels
