from threading import Thread, Event

from Utils.LogManager import LogManager
from script.ScriptManager import ScriptManager


class ThreadManager():
    threads = {}

    @classmethod
    def add(cls, udid, t: Thread, stopEvent: Event):
        if udid in cls.threads:
            print("▲ 线程已存在")
            return
        cls.threads[udid] = {"thread": t, "stopEvent": stopEvent}


    @classmethod
    def stop(cls, udid):
        try:
            info = cls.threads[udid]
            if info:
                info["stopEvent"].set() # 停止线程
                info["thread"].join(timeout=3) # 等待线程退出
                del cls.threads[udid]
                LogManager.info("停止线程成功", udid)
                return 200, "停止线程成功 " + udid
            else:
                LogManager.info("无此线程，无需关闭", udid)
                return 1001, "无此线程，无需关闭 " + udid
        except KeyError as e:
            LogManager.info("无此线程，无需关闭", udid)
            return 1001, "停止脚本失败 " + udid