"""Countthread 模块 - 文件计数线程."""

from __future__ import annotations

import os
import typing

from PySide2.QtCore import QObject, QThread, Signal


class CountThread(QThread):
    """采用独立线程搜索当前目录下对应的文件."""

    signal_finish = Signal(int)
    signal_update = Signal(int)
    signal_msg = Signal(str)

    def __init__(
        self, parent: typing.Optional[QObject] = None, widget: typing.Optional[QObject] = None, directory: str = ""
    ) -> None:
        super().__init__(parent)

        self.widget = widget
        self.directory = directory
        self.flag_quit = False
        self.file_count = 0

        self.signal_update.connect(self.widget.update_count_info)  # type: ignore
        self.signal_finish.connect(self.widget.finish_count)  # type: ignore
        self.signal_msg.connect(self.widget.update_msg)  # type: ignore

    def run(self) -> None:
        """搜索当前目录下的文件."""
        self.signal_msg.emit(f"[*] 启动线程 [{self.currentThread()}]")
        self.signal_msg.emit(f"[*] 更新目录 [{self.directory}] 下的文件...")

        for _root, _dirs, files in os.walk(self.directory):
            if self.flag_quit:
                break

            self.file_count += len(files)
            self.signal_update.emit(self.file_count)

        self.signal_finish.emit(self.file_count)
        self.signal_msg.emit("[*] 更新目录完成")
