# -*- coding: utf-8 -*-
import logging
import os

from .constants import c


class LogFile(object):
    """
    The log file class. Javis(URLDector) uses the instance of this class to write log.

    When init, it set the log file full path, formatter.
    """

    def __init__(self, hostname, log_name=c.LOG_NAME, log_path=c.LOG_PATH):
        if not log_name.endswith('.log'):
            log_name += '.log'
        # the name of the log file
        self.name = log_name

        # the path where the log file saved
        self.path = log_path

        full_path = os.path.join(self.path, hostname)   # path/hostname
        if not os.path.exists(full_path):
            os.makedirs(full_path)

        # the logger object
        self.logger = logging.getLogger(hostname)
        self.logger.setLevel(logging.DEBUG)

        # set handler
        fd = logging.FileHandler(os.path.join(full_path, self.name))
        # set formatter
        ft = logging.Formatter(c.LOG_FORMAT)

        fd.setLevel(logging.DEBUG)
        fd.setFormatter(ft)

        self.logger.addHandler(fd)

    def __getattr__(self, item):
        return getattr(self, item)

    def info(self, type, url, status=None):
        """write logs into log file."""
        log_string = '[Javis INFO]-{type} {status}  {url}'.\
            format(type=type, status=status, url=url)
        self.logger.info(log_string)
