import os
import logging
import logging.config

import define
from system import FILE as f
from system import DIRECTORY as d


CONF_FILE = "logging.conf"
BASE_NAME = "Puyopuyo.Owanimo"
BASE_LEVEL = logging.DEBUG
BASE_FORMAT = '%(processName)s.%(name)s ( PID %(process)d ) : %(asctime)s - %(levelname)s - %(message)s'


class Log(object):
    def __init__(self, name):
        d.create(define.APP_LOG)
        self.logger = logging.getLogger(name)
        self.logger.setLevel(BASE_LEVEL)
        self.__addHandler(self.consoleHandler())
        self.__addHandler(self.fileHandler(
            os.path.normpath(os.path.join(define.APP_LOG,"system.log"))))

    def __addHandler(self, handler):
        self.logger.addHandler(handler)

    def consoleHandler(self):
        f = logging.Formatter(BASE_FORMAT)
        h = logging.StreamHandler()
        h.setLevel(BASE_LEVEL)
        h.setFormatter(f)
        return h

    def fileHandler(self, filename):
        f.create(filename)
        fo = logging.Formatter(BASE_FORMAT)
        h = logging.FileHandler(filename, 'a+')
        h.setLevel(BASE_LEVEL)
        h.setFormatter(fo)
        return h

    def rotateFileHandler(self, filename):
        if os.path.exists(filename):
            f = logging.Formatter(BASE_FORMAT)
            h = logging.handlers.TimedRotatingFileHandler(
                filename    = os.path.normpath(os.path.join(filename)),
                when        = 'D',
                backupCount = 5
            )
            h.setLevel(BASE_LEVEL)
            h.setFormatter(f)
            return trh
        else:
            return None

    def debug(self, message):
        self.logger.debug(message)

    def warning(self, message):
        self.logger.warning(message)

    def info(self, message):
        self.logger.info(message)

    def critical(self, message):
        self.logger.critical(message)

    def error(self, message):
        self.logger.error(message)

    def __del__(self):
        del self

LOG = Log(BASE_NAME)

if __name__ == "__main__":
    logger = LOG
    logger.debug("debug")
    logger.warning("warning")
    logger.info("info")
    logger.critical("critical")
    logger.error("error")
