# Credit: Dai Chao Online == Date: 2026-02-23
from PyQt6.QtCore import QThread, pyqtSignal

from .emulator_manager import EmulatorManager


class DeviceLoader(QThread):
    refresh_row = pyqtSignal(int, object)
    task_complete = pyqtSignal(int)
    critical_error = pyqtSignal(str)
    load_progress = pyqtSignal(int)

    def __init__(self, ld_dir):
        super().__init__()
        self.ld_path = ld_dir

    def run(self):
        try:
            manager = EmulatorManager(self.ld_path)
            instances = manager.ldplayer
            total_count = len(instances)

            if total_count == 0:
                self.load_progress.emit(100)
                self.task_complete.emit(0)
                return

            for idx, instance in enumerate(instances):
                self.refresh_row.emit(idx, instance)

                percent_done = int(((idx + 1) / total_count) * 100)
                self.load_progress.emit(percent_done)

                self.msleep(50)

            self.task_complete.emit(total_count)

        except Exception as err:
            self.critical_error.emit(str(err))
