# -*- coding: utf-8 -*-

##
# @file   gui/util.py
# @brief  GUI utilitary functions
#
# @copyright
#
# @addtogroup
# @{

import logging
import os

from PySide import QtCore
from PySide import QtUiTools
from PySide import QtXml

log = logging.getLogger(os.path.basename(__file__))


# Invocation of methods in main thread
class InvokeEvent(QtCore.QEvent):
    EVENT_TYPE = QtCore.QEvent.Type(QtCore.QEvent.registerEventType())


    def __init__(self, fn, *args, **kwargs):
        QtCore.QEvent.__init__(self, InvokeEvent.EVENT_TYPE)
        self.fn = fn
        self.args = args
        self.kwargs = kwargs


class Invoker(QtCore.QObject):
    def event(self, event):
        event.fn(*event.args, **event.kwargs)

        return True


_invoker = Invoker()


def invoke_in_main_thread(fn, *args, **kwargs):
    QtCore.QCoreApplication.postEvent(_invoker,
                                      InvokeEvent(fn, *args, **kwargs))


class GenericThread(QtCore.QThread):
    def __init__(self, function, *args, **kwargs):
        QtCore.QThread.__init__(self)
        self.daemon = True
        self.function = function
        self.args = args
        self.kwargs = kwargs


    def __del__(self):
        self.wait()


    def run(self):
        self.function(*self.args, **self.kwargs)
        return


# Log formatter and handler
class NoExceptionFormatter(logging.Formatter):
    active = False


    def format(self, record):
        if NoExceptionFormatter.active:
            record.exc_text = ''  # ensure formatException gets called
        return super(NoExceptionFormatter, self).format(record)


    def formatException(self, record):
        if NoExceptionFormatter.active:
            return ''
        else:
            return super(NoExceptionFormatter, self).formatException(record)


class LogBoxStreamHandler(logging.StreamHandler):
    colors = {
        'DEBUG': 'black',
        'INFO': 'black',
        'WARN': 'black',
        'WARNING': 'black',
        'ERROR': 'red',
        'CRIT': 'red',
        'CRITICAL': 'red'
    }


    def emit(self, record):
        try:
            message = self.format(record)
            self.stream.write(message + '\n', self.colors[record.levelname])
        except:
            pass


# Stdout redirection
# inspired by http://stackoverflow.com/questions/21071448/redirecting-stdout-and-stderr-to-a-pyqt4-qtextedit-from-a-secondary-thread
class WriteStream(object):
    def __init__(self, signal, color, out_stream=None):
        self.signal = signal
        self.color = color
        self.out_stream = out_stream


    def write(self, text, color=None):
        if self.out_stream is not None:
            self.out_stream.write(text)

        if color is None:
            color = self.color
        self.signal.emit(text, color)

# @}
