# -*- coding: utf-8 -*-
# Elisa - Home multimedia server
# Copyright (C) 2006-2008 Fluendo Embedded S.L. (www.fluendo.com).
# All rights reserved.
#
# This file is available under one of two license agreements.
#
# This file is licensed under the GPL version 3.
# See "LICENSE.GPL" in the root of this distribution including a special
# exception to use Elisa with Fluendo's plugins.
#
# The GPL part of Elisa is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Elisa" in the root directory of this distribution package
# for details on that license.

from elisa.extern.log import log as externlog
from elisa.extern.log.log import *
from elisa.core.utils.misc import un_camelify

import os
import threading

def customStderrHandler(level, object, category, file, line, message):
    """
    A log handler that writes to stderr.

    @type level:    string
    @type object:   string (or None)
    @type category: string
    @type message:  string
    """
    
    if not isinstance(message, basestring):
        message = str(message)

    if isinstance(message, unicode):
        message = message.encode('utf-8')

    where = "(%s:%d)" % (file, line)
    
    formatted_level = getFormattedLevelName(level)
    formatted_time = time.strftime("%b %d %H:%M:%S")
    thread_name = threading.currentThread().getName()
    formatted = '%s %-15s %-27s %-15s ' % (formatted_level, thread_name,
                                           category,
                                           formatted_time)

    safeprintf(sys.stderr, formatted)
    safeprintf(sys.stderr, ' %s %s\n', message, where)

    sys.stderr.flush()

def setDebug(debug_string):
    warn_all = '*:2'
    levels = debug_string.split(',')
    if warn_all not in levels:
        levels.insert(0, warn_all)
        
    externlog.setDebug(','.join(levels))

def init(log_to_file = False):

    externlog.init('ELISA_DEBUG', True)
        
    externlog.setPackageScrubList('elisa', 'twisted')
    
    if log_to_file == True:
        externlog.outputToFiles('elisa.log', 'elisa.log')

    setDebug(os.getenv('ELISA_DEBUG',''))

    # register our log handler
    if externlog.stderrHandler in externlog._log_handlers_limited:
        externlog.removeLimitedLogHandler(externlog.stderrHandler)
        externlog.addLimitedLogHandler(customStderrHandler)

# Make Loggable a new-style object
class Loggable(externlog.Loggable, object):

    def __init__(self):

        # I don't really like CamelCase
        if hasattr(self, 'log_category'):
            self.logCategory = self.log_category
        else:
            # set log category to class name, lowercased
            self.logCategory = un_camelify(self.__class__.__name__)

        super(Loggable, self).__init__()
