# -*- coding: utf-8 -*-
import os
import logging
import colorlog
from socket import gethostname
from devo.sender import Sender
from .config import get_config

__author__ = 'Devo (<NAME>)'


class DevoHandler(logging.StreamHandler):
    def __init__(self, config):
        logging.StreamHandler.__init__(self)
        self.sender = Sender(config=config)
        self.tag = config['tag']
        conf = get_config()
        self.instance = '{}@{}:{}'.format(
            conf['server'].get('name', 'lapua'),
            gethostname(),
            conf['server']['port'])

    def emit(self, record):
        msg = self.format(record)
        msg = '{} - {}'.format(self.instance, msg.replace('\n', '%0A'))
        retries = 3
        while retries:
            try:
                self.sender.send(msg=msg, tag=self.tag)
                break
            except:
                retries -= 1


def merge_logging_confs(general, custom):
    if not custom:
        return general

    result = {**custom}

    if 'file' in custom and not custom['file'].get('path'):
        result['file']['path'] = general['file']['path']

    if 'devo' in custom and not custom['devo'].get('sender'):
        result['devo']['sender'] = general['devo']['sender']

    return result


def get_global_logger():
    conf = get_config()
    if 'level' in conf['logging']:
        return {
            "console": {
                "level": conf['logging']['level']
            },
            "file": {
                "level": conf['logging']['level'],
                "path": conf['paths']['log']
            },
            "devo": {
                "level": conf['logging']['level'],
                "sender": {**conf['sender'], "tag": conf['targets']['server']}
            }
        }

    logger_config = {**conf['logging']}

    if 'file' in logger_config and not logger_config['file'].get('path'):
        logger_config['file']['path'] = conf['paths']['log']

    if 'devo' in logger_config and not logger_config['devo'].get('sender'):
        logger_config['devo']['sender'] = {**conf['sender'],
                                           "tag": conf['targets']['server']}

    return logger_config


def get_logging_level(level):
    return eval('logging.{}'.format(level.upper()))


def get_logger(instance, console=None, file=None, devo=None):
    logger = logging.getLogger('lapua-{}'.format(instance))
    logger.setLevel(logging.DEBUG)

    if not len(logger.handlers):
        conf = get_config()
        if file:
            file_handler = logging.handlers.RotatingFileHandler(
                os.path.join(file.get('path', conf['paths']['log']),
                             '{}.log'.format(instance)),
                maxBytes=2*1024*1024, backupCount=3)
            file_handler.setLevel(get_logging_level(file.get('level', 'INFO')))
            file_handler.setFormatter(logging.Formatter(
                '%(asctime)s - %(levelname)s - %(message)s'))
            logger.addHandler(file_handler)

        if console:
            console_handler = logging.StreamHandler()
            console_handler.setLevel(get_logging_level(
                console.get('level', 'INFO')))
            format_template = \
                '%(asctime)s - %(levelname)s - %(threadName)s - %(message)s'
            if os.isatty(2):
                cformat = '%(log_color)s' + format_template
                console_formatter = colorlog.ColoredFormatter(cformat)
            else:
                console_formatter = logging.Formatter(format_template)
            console_handler.setFormatter(console_formatter)
            logger.addHandler(console_handler)

        if devo:
            devo_handler = DevoHandler(
                devo.get('sender',
                         dict(**conf['sender'], tag=conf['targets']['server'])))
            devo_handler.setLevel(get_logging_level(devo.get('level', 'INFO')))
            devo_handler.setFormatter(logging.Formatter(
                '%(levelname)s - %(threadName)s - %(message)s'))
            logger.addHandler(devo_handler)

    return logger

# -*- coding: utf-8 -*-
import os
import logging
import colorlog
from socket import gethostname
from devo.sender import Sender
from .config import get_config

__author__ = 'Devo (<NAME>)'


class DevoHandler(logging.StreamHandler):
    def __init__(self, config):
        logging.StreamHandler.__init__(self)
        self.sender = Sender(config=config)
        self.tag = config['tag']
        conf = get_config()
        self.instance = '{}@{}:{}'.format(
            conf['server'].get('name', 'lapua'),
            gethostname(),
            conf['server']['port'])

    def emit(self, record):
        msg = self.format(record)
        msg = '{} - {}'.format(self.instance, msg.replace('\n', '%0A'))
        retries = 3
        while retries:
            try:
                self.sender.send(msg=msg, tag=self.tag)
                break
            except:
                retries -= 1


def merge_logging_confs(general, custom):
    if not custom:
        return general

    result = {**custom}

    if 'file' in custom and not custom['file'].get('path'):
        result['file']['path'] = general['file']['path']

    if 'devo' in custom and not custom['devo'].get('sender'):
        result['devo']['sender'] = general['devo']['sender']

    return result


def get_global_logger():
    conf = get_config()
    if 'level' in conf['logging']:
        return {
            "console": {
                "level": conf['logging']['level']
            },
            "file": {
                "level": conf['logging']['level'],
                "path": conf['paths']['log']
            },
            "devo": {
                "level": conf['logging']['level'],
                "sender": {**conf['sender'], "tag": conf['targets']['server']}
            }
        }

    logger_config = {**conf['logging']}

    if 'file' in logger_config and not logger_config['file'].get('path'):
        logger_config['file']['path'] = conf['paths']['log']

    if 'devo' in logger_config and not logger_config['devo'].get('sender'):
        logger_config['devo']['sender'] = {**conf['sender'],
                                           "tag": conf['targets']['server']}

    return logger_config


def get_logging_level(level):
    return eval('logging.{}'.format(level.upper()))


def get_logger(instance, console=None, file=None, devo=None):
    logger = logging.getLogger('lapua-{}'.format(instance))
    logger.setLevel(logging.DEBUG)

    if not len(logger.handlers):
        conf = get_config()
        if file:
            file_handler = logging.handlers.RotatingFileHandler(
                os.path.join(file.get('path', conf['paths']['log']),
                             '{}.log'.format(instance)),
                maxBytes=2*1024*1024, backupCount=3)
            file_handler.setLevel(get_logging_level(file.get('level', 'INFO')))
            file_handler.setFormatter(logging.Formatter(
                '%(asctime)s - %(levelname)s - %(message)s'))
            logger.addHandler(file_handler)

        if console:
            console_handler = logging.StreamHandler()
            console_handler.setLevel(get_logging_level(
                console.get('level', 'INFO')))
            format_template = \
                '%(asctime)s - %(levelname)s - %(threadName)s - %(message)s'
            if os.isatty(2):
                cformat = '%(log_color)s' + format_template
                console_formatter = colorlog.ColoredFormatter(cformat)
            else:
                console_formatter = logging.Formatter(format_template)
            console_handler.setFormatter(console_formatter)
            logger.addHandler(console_handler)

        if devo:
            devo_handler = DevoHandler(
                devo.get('sender',
                         dict(**conf['sender'], tag=conf['targets']['server'])))
            devo_handler.setLevel(get_logging_level(devo.get('level', 'INFO')))
            devo_handler.setFormatter(logging.Formatter(
                '%(levelname)s - %(threadName)s - %(message)s'))
            logger.addHandler(devo_handler)

    return logger

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