#!D:\IDE\Anaconda3\envs\Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
 @Author: Administrator
 @FileName: logUtils.py
 @DateTime: 2025/6/21 16:53
 @SoftWare: PyCharm
 @Author  ：xsh
"""
from PyQt5 import Qt
from importlib import import_module
from PyQt5 import Qt
import inspect
import traceback
import time
import sys
import json
import psutil
import subprocess

class logUtils:
    @staticmethod
    def processGlobalEvent(interVal: int):
        return Qt.QCoreApplication.processEvents(Qt.QEventLoop.AllEvents, max(100, abs(interVal)))

    @staticmethod
    def processEvent(interVal: int):
        wait_delay: int = abs(interVal)
        if wait_delay < 20:
            return Qt.QCoreApplication.processEvents(Qt.QEventLoop.AllEvents, 100)
        end_times: Qt.QDateTime = Qt.QDateTime.currentDateTime().addMSecs(wait_delay)
        while True:
            if Qt.QDateTime.currentDateTime() > end_times:
                break
            Qt.QCoreApplication.processEvents(Qt.QEventLoop.AllEvents, 100)
        return

    @staticmethod
    def toSourcePath() -> str:
        return f"{Qt.QFileInfo(sys.argv[0]).absolutePath()}/Resource/"

    @staticmethod
    def toSourceFile(file: str) -> str:
        if not isinstance(file, str):
            return ''
        if file.find(":") >= 0:  # 如果文件路径已经是绝对路径，则直接返回
            return Qt.QFileInfo(file).absoluteFilePath()
        if file[0:2] == '//' or file[0:2] == r'\\':
            return Qt.QFileInfo(file).absoluteFilePath()
        return Qt.QFileInfo(f"{logUtils.toSourcePath()}{file}").absoluteFilePath()
    @staticmethod
    def isEmpty(string: str) -> bool:
        """检查字符串是否为空或仅包含空白字符"""
        return not string or string.isspace() or len(string) <= 0 or len(string.replace(" ", "")) <= 0

    @staticmethod
    def print_current_function_info(message: str):
        """打印当前函数名称和行号"""
        frame = inspect.currentframe().f_back
        print(
            f"Current function: {frame.f_code.co_name}, Line: {frame.f_lineno} Message: {message if message is not None else ''}")

    @staticmethod
    def current_function_info(message: str) -> str:
        frame = inspect.currentframe().f_back
        return f"[function: {frame.f_code.co_name}]\t[Line: {frame.f_lineno} ]\t {message}"
    @staticmethod
    def print_Exception(e: Exception, message: str = ""):
        warning_string = logUtils.toString(e)
        # from AppCore.AppLogHelper import logSYSTEM
        # logSYSTEM << warning_string
        if logUtils.isEmpty(message):
            print(warning_string)
        else:
            print(f"{warning_string}\tMessage: {message}")

    @staticmethod
    def toString(e: Exception) -> str:
        # 获取当前的异常信息
        exc_type, exc_obj, tb = type(e), e, e.__traceback__

        # 获取调用栈信息
        frame = tb.tb_frame
        lineno = tb.tb_lineno
        func_name = frame.f_code.co_name
        # 获取完整的异常信息
        full_traceback = traceback.format_exception(exc_type, exc_obj, tb)
        # 构建错误信息字符串
        error_info: list[str] = [f"Error: {str(e)}", f"Function: {func_name}", f"Line: {lineno}",
                                 f"Traceback:{' '.join(full_traceback)}"]
        return "\t".join(error_info)


def log_exception(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            logUtils.print_Exception(e)
            # raise Exception("I know python!") # 重新抛出异常，以便调用者可以处理
            return None
    return wrapper