# -*- coding: utf-8 -*-
from typing import Callable
from ddans.common.event import DEvent
from ddans.descriptor.singleton import singleton
import threading
import time

Loop = "loop"


@singleton
class SWorker:

    def __init__(self):
        super()
        self._event = DEvent()
        self._running = threading.Event()
        self._stop_event = threading.Event()
        self._thread = threading.Thread(target=self._loop)
        self._thread.daemon = True  # 将线程设置为守护线程

    def start(self):
        if not self._thread.is_alive():
            self._running.set()
            self._stop_event.clear()
            self._thread = threading.Thread(target=self._loop)
            self._thread.daemon = True
            try:
                self._thread.start()
            except RuntimeError as e:
                print(f"线程启动失败: {e}")

    def stop(self):
        self._running.clear()
        self._stop_event.set()

    def _loop(self):
        while not self._stop_event.is_set():
            if self._running.is_set():
                try:
                    self._event.emit(Loop)
                    time.sleep(1)
                except Exception as e:
                    print(f"在循环中捕获异常: {e}")
                    self._running.clear()

    def onLoop(self, callback: Callable[[], None]):
        try:
            self._event.on(Loop, callback)
        except Exception as e:
            print(f"注册回调函数失败: {e}")

    def offLoop(self, callback: Callable[[], None]):
        try:
            self._event.off(Loop, callback)
        except Exception as e:
            print(f"取消注册回调函数失败: {e}")
