import logging
import textwrap

from fiber.middleware import AdminPageMiddleware

logger = logging.getLogger('logement')

class AdminPageMiddlewareOverloaded(AdminPageMiddleware):
    def show_admin(self, request, response):
         if not hasattr(request, 'user'):
            return False
         if not request.user.has_perm('fiber.change_page'):
            return False
         return super(AdminPageMiddlewareOverloaded, self).show_admin(request, response)

class LoggerAdapterWrapper(logging.LoggerAdapter):
    def log(self, level, msg, *args, **kwargs):
        msg = msg % args
        if isinstance(msg, unicode):
            msg = msg.encode('utf-8')
        for line in msg.splitlines():
            for wrapped_line in textwrap.wrap(line, 100):
                super(LoggerAdapterWrapper, self).log(level, wrapped_line, *args, **kwargs)

class LazyString(object):
    def __init__(self, func):
        self.func = func

    def __str__(self):
        return str(self.func())


def get_logger(request):
    ip = request.META.get('HTTP_X_FORWARDED_FOR') or request.META.get('REMOTE_ADDR', '-')
    return LoggerAdapterWrapper(logger,
            { 'request_id': id(request),
                'user': LazyString(lambda: unicode(request.user).encode('utf-8')),
              'ip': ip })

def get_logger_no_request():
    return LoggerAdapterWrapper(logger,
            { 'request_id': '-',
              'user': 'automate',
              'ip': '-' })

class LoggerMiddleware(object):
    def process_request(self, request):
        request.logger = get_logger(request)
