# -*- coding: utf-8 -*-
#------------------------------------------------------------
# smytvshow
# Loger
# http://smystero.dlinkddns.org/smytvwhow/
#------------------------------------------------------------

import xbmc

import inspect
import config

logger_active = (config.get_setting("debug") == "true")


def info(text):
    if logger_active:
        try:
            xbmc.log("[smytvshow].[%s] %s" % (caller_name(), text), xbmc.LOGNOTICE)
        except Exception as e:
            xbmc.log("[smytvshow].[{%s}] {%s}" % (caller_name(), e.message), xbmc.LOGNOTICE)

def debug(text):
    if logger_active:
        try:
            xbmc.log("[smytvshow].[%s] {%s}" % (caller_name(), text), xbmc.LOGDEBUG)
        except Exception as e:
            xbmc.log("[smytvshow].[{%s}] {%s}" % (caller_name(), e.message), xbmc.LOGNOTICE)


def error(text, detail=False):
    if logger_active:
        try:
            xbmc.log("[smytvshow].[{%s}] {%s}" % (caller_name(), text), xbmc.LOGERROR)
            if detail:
                import traceback,sys
                exc_type, exc_value, exc_tb = sys.exc_info()
                lines = traceback.format_exception(exc_type, exc_value, exc_tb)
                for line in lines:
                    line_splits = line.split("\n")
                    for line_split in line_splits:
                        xbmc.log("[smytvshow].[{%s}] {%s}" % (caller_name(), line_split), xbmc.LOGERROR)

        except Exception as e:
            xbmc.log("[smytvshow].[{%s}] {%s}" % (caller_name(), e.message), xbmc.LOGNOTICE)


def caller_name(skip=2):
    stack = inspect.stack()
    start = 0 + skip
    if len(stack) < start + 1:
        return ''

    parent_frame = stack[start][0]
    name = []

    module = inspect.getmodule(parent_frame)
    if module:
        name.append(module.__name__)

    # detect class_name
    if 'self' in parent_frame.f_locals:
        name.append(parent_frame.f_locals['self'].__class__.__name__)

    codename = parent_frame.f_code.co_name
    if codename != '<module>': # top level usually
        name.append( codename ) # function or a method

    del parent_frame
    return ".".join(name)