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


__author__ = 'm_beloborodko@wargaming.net'

import logging
import re
from logging import Handler, INFO, getLevelName
from logging.handlers import RotatingFileHandler
from os import path, makedirs


class TestDependentRotatingFileHandler(RotatingFileHandler):
    log_filename = None

    def __init__(self):
        # We need to path here empty string as we don't care about this param
        # also we cant pass here None because some errors on Linux
        super().__init__('')

    def _open(self):
        stream = None
        log_filename = self.__class__.log_filename
        if log_filename:
            log_folder = path.dirname(log_filename)

            if not path.isdir(log_folder):
                makedirs(log_folder)

            log_filename = log_filename if log_filename.startswith('\\\\?\\') \
                else '\\\\?\\%s' % log_filename
            stream = open(log_filename, self.mode, encoding='utf-8')
        return stream

    def emit(self, record):
        if not self.__class__.log_filename:
            return
        self.stream = None
        super().emit(record)
        
        
class UTF8StreamHandler(logging.StreamHandler):
    """
    A custom StreamHandler that forces UTF-8 encoding.
    This is needed for Python < 3.10, where 'encoding' is not supported in dictConfig.
    """
    def __init__(self, *args, **kwargs):
        encoding = kwargs.pop('encoding', 'utf-8')
        super().__init__(*args, **kwargs)
        self.encoding = encoding


class DistributeRotatingFileHandler(TestDependentRotatingFileHandler):
    log_filename = None
    total_content_size = 0

    @classmethod
    def clear_stats(cls):
        cls.log_filename = None
        cls.total_content_size = 0

    def emit(self, record):
        if not DistributeRotatingFileHandler.log_filename:
            return
        self.stream = None
        match = re.match(r'.*content_length=(\d+)', record.getMessage())
        if match:
            DistributeRotatingFileHandler.total_content_size += \
                int(match.groups()[0])
        super(DistributeRotatingFileHandler, self).emit(record)


class MocksRotatingFileHandler(TestDependentRotatingFileHandler):
    """Mock rotating file handler"""


class ProductHashRotatingFileHandler(TestDependentRotatingFileHandler):
    """Mock rotating file handler"""


class MocksRespRotatingFileHandler(TestDependentRotatingFileHandler):
    """Mock rotating file handler"""


class ProxyRotatingFileHandler(TestDependentRotatingFileHandler):
    """Proxy rotating file handler"""


class StepsToReproduceFileHandler(Handler):
    steps = []
    header = '*STR:*'

    @classmethod
    def reset_str(cls):
        cls.steps = []

    @classmethod
    def compose_str(cls):
        cls.steps = \
            [f'{i + 1}. {step.rstrip()}' for i, step in enumerate(cls.steps) if isinstance(step, str) and step != '']
        cls.steps[:0] = [cls.header, '']
        result = '\n'.join(cls.steps)
        cls.reset_str()
        return result

    @classmethod
    def emit(cls, record):
        if record.levelname == getLevelName(INFO):
            if '[testhide_message]' not in record.msg:
                cls.steps.append(record.msg)
