# -*- coding: UTF-8 -*-
import traceback
import sys
import os
from cbb.frame.util.common import wrapAllExceptionLogged


def format_traceback():
    new_extracted_list = []
    etype, value, tb = sys.exc_info()
    extracted_list = traceback.extract_tb(tb)
    for item in extracted_list:
        filename, lineno, name, line = item
        filename = os.path.basename(filename)
        new_extracted_list.append((filename, lineno, name, line))

    return "".join(traceback.format_list(new_extracted_list) + traceback.format_exception_only(etype, value))


class Logger(object):
    '''
    @summary 日志类
    '''

    def __init__(self, loggerInstance, pyFileName):
        self.loggerInstance = loggerInstance
        self.pyFileName = pyFileName

    @wrapAllExceptionLogged(logger=None)
    def debug(self, msg):
        '''
        @summary: 调试信息输出
        @param msg: 调试信息
        '''

        if msg is None:
            msg = "None"
        self.loggerInstance.debug(msg)

    def info(self, msg):
        '''
        @summary: 调试信息输出
        @param msg: 调试信息
        '''
        if msg is None:
            msg = "None"
        self.loggerInstance.info("[ToolLog][%s][info][%s]" % (self.pyFileName, str(msg)))
        return

    def error(self, msg):
        '''
        @summary: 错误信息输出
        @param msg: 错误信息
        '''
        if msg is None:
            msg = "None"
        self.loggerInstance.info("[ToolLog][%s][error][%s]" % (self.pyFileName, str(msg)))
        return

    def logInfo(self, msg):
        '''
        @summary: 调试信息输出
        @param msg: 调试信息
        '''
        if msg is None:
            msg = "None"
        self.loggerInstance.info("[ToolLog][%s][info][%s]" % (self.pyFileName, str(msg)))
        return

    def logPass(self):
        '''
        @summary: 检查通过时的输出
        '''
        self.loggerInstance.info("[ToolLog][%s][pass]" % self.pyFileName)
        return

    def logNoPass(self, errMsg):
        '''
        @summary: 检查不通过时的输出
        @param errMsg: 错误消息
        '''
        if errMsg is None:
            errMsg = "None"
        self.loggerInstance.info("[ToolLog][%s][no_pass][%s]" % (self.pyFileName, str(errMsg)))
        return

    def logException(self, exception):
        '''
        @summary: 检查异常时的输出
        @param exception: 异常消息
        '''
        trace = format_traceback()
        self.loggerInstance.error("[ToolLog][%s][exception][arguements:%s]" % (self.pyFileName, unicode(exception.args)))
        self.loggerInstance.error("[ToolLog][%s][exception][traceback:%s]" % (self.pyFileName, unicode(trace)))
        return
