import logging

from wox.logger.constants import CONTEXTUAL_INFO


class SetLevelTo(logging.Filter):
    """
        A filter mimicking the behaviour of setLevel().

        Example :
        logger.filters = [SetLevelTo('INFO')]

        Parameters
        ----------
        level : str

        Returns
        -------
        Boolean
            True if the LogRecord has level number greater or
            equal than level.
    """

    def __init__(self, level):
        self.level = level

    def filter(self, record):
        return record.levelno >= logging._nameToLevel[self.level]

class WoxContext(logging.Filter):
    """
        Adds contextual fields to log formatting.

        Parameters
        ----------
        contextual_info : dict, default wox.logger.constants.CONTEXTUAL_INFO
            The default contextual information.
    """

    def __init__(self, contextual_info = None):
        if contextual_info is None:
            self.contextual_info = CONTEXTUAL_INFO.copy()
        else:
            self.contextual_info = contextual_info

    def filter(self, record):
        """
            Returns
            -------
            Boolean
                True if contexual info are set in LogRecord.
        """

        for key, value in self.contextual_info.items():
            setattr(record, key, value)

        return True

    def update_context(self, overrides):
        """
            Updates the current contextual information.

            Parameters
            ----------
            overrides : dict
                Key-value pairs overriding the current contextual information.
        """

        self.contextual_info.update(overrides)
