from PySide6.QtCore import QRect, Qt
from PySide6.QtWidgets import QWidget, QApplication
from typing import Dict
import sys,os
from qt_material import apply_stylesheet
from acycle.plot.PlotCfg import PlotCfg
from acycle.plot.TxtEditor import TxtEditor
from acycle.plot.MplWidget import MplWidget
from acycle.window.WindowDivider import WindowDivider
class sample_rate(QWidget):
    def __init__(self, parent=None, spacing: int = 10, theme: str = 'default.xml', file_path: str = None):
        """
        初始化窗口布局管理器
        
        :param parent: 父组件
        :param spacing: 窗口间距
        :param theme: 主题文件
        :param file_path: 初始文件路径
        """
        super().__init__(parent)
        self.spacing = spacing
        self.theme = theme
        self.current_file_path = file_path if file_path else ""
        self.windows: Dict[str, QWidget] = {}
        
    def setup_2_pane_layout(self):
        """
        设置2窗格布局并创建窗口
        
        :param right_split_ratio: 右侧上下分割比例 (0.0-1.0)
        """
        screen_geometry = self.screen().availableGeometry()
        # 使用WindowDivider计算布局
        divider = WindowDivider(screen_geometry, spacing=self.spacing)
        # 左侧面板 (50%)
        left_rect = divider.get_subrect(1, 2, 1)  # 1行2列，第1个区域
        # 右侧面板 (50%)，上下分割
        right_rect = divider.get_subrect(1, 2, 2)  # 2行1列，第1个区域
        window_rects = {
            "left": left_rect,
            "right": right_rect,
        }
        # 清除现有窗口
        self._close_all_windows()
        # 创建新窗口
        self._create_windows(window_rects)
    
    def _create_windows(self, window_rects: Dict[str, QRect]):
        """
        根据布局创建各个窗口
        
        :param window_rects: 窗口位置字典
        """
        # 窗口创建配置
        window_configs = {
            "left": {
                "title":  os.path.basename(self.current_file_path)+": sampling rate",
                "creator": self._create_left_panel,
                "args": {"parent_win":self,"file_path": self.current_file_path}
            },
            "right": {
                "title": os.path.basename(self.current_file_path)+": kernel fit of sampling rate",
                "creator": self._create_right_panel,
                "args": {"file_path": self.current_file_path}
            }
        }
        for pos, geom in window_rects.items():
            config = window_configs[pos]
            self.windows[pos] = config["creator"](**config["args"])
            self._configure_window(self.windows[pos], geom, config["title"])
            self.windows[pos].destroyed.connect(lambda _, p=pos: self._on_window_closed(p))
    
    def _create_left_panel(self, **kwargs) -> QWidget:
        """创建左侧面板"""
        mlp = MplWidget(**kwargs)
        mlp.plot_sample_rate()
        return mlp
    
    def _create_right_panel(self, **kwargs) -> QWidget:
        """创建右侧面板"""
        mlp = MplWidget(**kwargs)
        mlp.plot_distribution()
        return mlp
    
    
    def _configure_window(self, window: QWidget, geometry: QRect, title: str = ""):
        """配置窗口通用属性"""
        if hasattr(window, 'setGeometry'):
            window.setGeometry(geometry)
        if title and hasattr(window, 'setWindowTitle'):
            window.setWindowTitle(title)
        
        apply_stylesheet(window, theme=self.theme)
        
        if hasattr(window, 'show'):
            window.show()
        if hasattr(window, 'raise_'):
            window.raise_()
    
    def _on_window_closed(self, position: str):
        """窗口关闭事件处理"""
        if position in self.windows:
            del self.windows[position]
    
    def _close_all_windows(self):
        """关闭所有管理的窗口"""
        for window in self.windows.values():
            if hasattr(window, 'close'):
                window.close()
        self.windows.clear()
    
    def set_file_path(self, file_path: str):
        """设置当前文件路径"""
        self.current_file_path = file_path
        if "right_top" in self.windows and hasattr(self.windows["right_top"], 'set_file_path'):
            self.windows["right_top"].set_file_path(file_path)
        if "right_bottom" in self.windows and hasattr(self.windows["right_bottom"],'set_file_path'):
            self.windows["right_bottom"].set_file_path(file_path)
    
    def set_theme(self, theme: str):
        """设置主题并应用到所有窗口"""
        self.theme = theme
        for window in self.windows.values():
            apply_stylesheet(window, theme=theme)

    


if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 创建窗口管理器
    manager = sample_rate(
        spacing=30, 
        theme='dark.xml',
        file_path='D:\\git\\acycle\\acyclePy\\Example-SvalbardPETM-logFe.txt'
    )
    
    # 设置3窗格布局 (右侧上下60/40分割)
    manager.setup_2_pane_layout(right_split_ratio=0.6)
    
    sys.exit(app.exec())