"""Filetreeviewer 模块 - 文件树查看器对话框."""

from __future__ import annotations

import typing
from pathlib import Path
from typing import TYPE_CHECKING

from PySide2.QtCore import QUrl
from PySide2.QtGui import QDesktopServices, QFont, QStandardItem, QStandardItemModel
from PySide2.QtWidgets import QDialog, QMessageBox

from .filetreeviewer_ui import Ui_FileTreeViewer

if TYPE_CHECKING:
    from pytola_office.filescan.gui import FileScanner


class FileTreeViewer(QDialog, Ui_FileTreeViewer):
    """文件树查看器对话框."""

    def __init__(self, parent: FileScanner | None = None) -> None:
        super().__init__(parent=parent)
        font = QFont("Microsoft YaHei", 10, weight=70)  # QFont.Bold = 70
        self.setFont(font)
        self.setupUi(self)

        self.model = None
        self.resetModel()

        self.pbOpenFile.clicked.connect(self.open_file)
        self.pbLocateFile.clicked.connect(self.locate_file)

    def resetModel(self) -> None:
        """重置文件树模型."""
        self.model = QStandardItemModel()
        self.tvFiles.setModel(self.model)
        self.tvFiles.setHeaderHidden(True)

    def add_files(self, keyword: str, files: typing.List[str]) -> None:
        """添加文件到文件树模型.

        Args:
            keyword: 搜索关键词
            files: 文件路径列表
        """
        if self.model is None:
            msg = "模型未初始化"
            raise RuntimeError(msg)
        root = self.model.invisibleRootItem()
        keyword_item = QStandardItem(f"关键字：[{keyword}]")
        keyword_item.appendRows([QStandardItem(file) for file in files])
        root.appendRow(keyword_item)
        self.tvFiles.setExpanded(root.index(), True)

    def open_file(self) -> None:
        """打开选中的文件."""
        file_name = self.get_current_file_path()
        if file_name:
            QDesktopServices.openUrl(QUrl(f"file:///{file_name}"))

    def locate_file(self) -> None:
        """定位选中文件所在的目录."""
        file_name = self.get_current_file_path()
        if file_name:
            folder_path = Path(file_name).parent
            if not folder_path.is_dir():
                QMessageBox.warning(self, "警告", "文件所在目录无效!")
                return

            QDesktopServices.openUrl(QUrl(f"file:///{folder_path.as_posix()}"))

    def get_current_file_path(self) -> str:
        """获取当前文件路径."""
        if self.model is None:
            msg = "模型未初始化"
            raise RuntimeError(msg)
        index = self.tvFiles.currentIndex()
        if index.row() == -1:
            QMessageBox.warning(self, "警告", "请选择项目!")
            return ""
        if not self.model.itemFromIndex(index).parent():
            QMessageBox.warning(self, "警告", "请选择文件路径项!")
            return ""

        return self.model.itemFromIndex(index).text()
