# coding: utf-8

import os
import logging
from logging import handlers
import json
from etc.settings.base import LOG_PATH


class SingletonMeta(type):
    instance = None

    def __call__(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance = super(SingletonMeta, cls).__call__(*args, **kwargs)
        return cls.instance

    def __new__(mcs, name, bases, dct):
        return type.__new__(mcs, name, bases, dct)

    def __init__(cls, name, bases, dct):
        super(SingletonMeta, cls).__init__(name, bases, dct)


class ExceptionLoggingMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        self.apiLogger = logging.getLogger('request_api')

    def __call__(self, request):
        try:
            body = json.loads(request.body)
        except Exception:
            body = dict()
        body.update(dict(request.POST))
        response = self.get_response(request)
        if request.method != 'GET':
            try:
                self.apiLogger.info(
                    "\nuser: {}\n{}\n{} {} {} {} {}\nreturn {}".format(
                        request.user, response.renderer_context["view"],
                        request.method, request.path, body,
                        response.status_code, response.reason_phrase,
                        response.data))
            except Exception as e:
                self.apiLogger.info(e)
        return response


class Logger(object):
    __metaclass__ = SingletonMeta

    logger_dict = {}

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

    def get_logger(self, module, filename):
        if module in self.logger_dict:
            return self.logger_dict[module]
        logger = self.create_logger(module, filename)
        self.logger_dict[module] = logger
        return logger

    def create_logger(self, module, filename):
        LOGGING_MSG_FORMAT = "%(asctime)s [%(levelname)s] localhost " \
                             "[%(funcName)s] %(pathname)s:%(lineno)s " \
                             "%(message)s"
        LOGGING_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
        logging.basicConfig(level=self.level,
                            format=LOGGING_MSG_FORMAT,
                            datefmt=LOGGING_DATE_FORMAT)

        logger = logging.getLogger(module)
        handler = handlers.RotatingFileHandler(os.path.join(
            LOG_PATH, filename),
                                               maxBytes=1024 * 1024 * 50,
                                               backupCount=5,
                                               encoding='utf-8')
        handler.setFormatter(logging.Formatter(LOGGING_MSG_FORMAT))
        logger.addHandler(handler)
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        console.setFormatter(logging.Formatter(LOGGING_MSG_FORMAT))
        logger.addHandler(console)
        return logger

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