import logging
import os
import shutil


class LogManager:
    # 获取项目根目录
    projectRoot = os.path.dirname(os.path.dirname(__file__))
    logDir = os.path.join(projectRoot, "log")

    # 类变量，存储日志记录器
    _loggers = {}

    @classmethod
    def _setupLogger(cls, udid, name, logName, level=logging.INFO):
        """设置日志记录器"""
        deviceLogDir = os.path.join(cls.logDir, udid)
        os.makedirs(deviceLogDir, exist_ok=True)  # 确保日志目录存在
        logFile = os.path.join(deviceLogDir, logName)
        logger = logging.getLogger(f"{udid}_{name}")
        logger.setLevel(level)
        fileHandler = logging.FileHandler(logFile, mode="a", encoding="utf-8")
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s",
                                      datefmt="%Y-%m-%d %H:%M:%S")
        fileHandler.setFormatter(formatter)
        logger.addHandler(fileHandler)
        return logger

    @classmethod
    def _getLogger(cls, udid, name, logName, level=logging.INFO):
        """获取或初始化日志记录器"""
        if udid not in cls._loggers:
            cls._loggers[udid] = {}
        if name not in cls._loggers[udid]:
            cls._loggers[udid][name] = cls._setupLogger(udid, name, logName, level)
        return cls._loggers[udid][name]

    @classmethod
    def info(cls, text, udid):
        """记录 INFO 级别的日志"""
        logger = cls._getLogger(udid, "infoLogger", "info.log", level=logging.INFO)
        logger.info(f"[{udid}] {text}")

    @classmethod
    def warning(cls, text, udid):
        """记录 WARNING 级别的日志"""
        logger = cls._getLogger(udid, "warningLogger", "warning.log", level=logging.WARNING)
        logger.warning(f"[{udid}] {text}")

    @classmethod
    def error(cls, text, udid):
        """记录 ERROR 级别的日志"""
        logger = cls._getLogger(udid, "errorLogger", "error.log", level=logging.ERROR)
        logger.error(f"[{udid}] {text}")

    @classmethod
    def clearLogs(cls):
        """清空整个 log 目录下的所有内容"""
        print("开始清空日志...")

        # 关闭所有日志记录器的处理器
        for udid in cls._loggers:
            for name in cls._loggers[udid]:
                logger = cls._loggers[udid][name]
                for handler in logger.handlers[:]:  # 使用切片避免在迭代时修改列表
                    handler.close()
                    logger.removeHandler(handler)
                print(f"关闭了 {udid}_{name} 的处理器")

        # 删除整个 log 目录
        if os.path.exists(cls.logDir):
            shutil.rmtree(cls.logDir)  # 删除目录及其所有内容
            print(f"删除了 {cls.logDir}")
            os.makedirs(cls.logDir, exist_ok=True)  # 重新创建空的 log 目录
            print(f"重新创建了 {cls.logDir}")
        else:
            print(f"{cls.logDir} 不存在，无需删除")
        print("日志清空完成")