import logging
import logging.handlers
import os

from quixote import get_publisher, get_session, get_request

logger = None
logfile = None

def enable():
    global logger, logfile, info, warn, error
    logfile = os.path.join(get_publisher().app_dir, 'larpe.log')
    logger = logging.getLogger('larpe' + get_publisher().app_dir)
    if not logger.handlers:
        hdlr = logging.handlers.RotatingFileHandler(logfile, 'a', 2**20, 100)
            # max size = 1M
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        logger.addHandler(hdlr) 
        logger.setLevel(logging.DEBUG)

def disable():
    global logger
    logger = None

def is_bot():
    botfile = os.path.join(get_publisher().data_dir, 'webbots')
    if not os.path.exists(botfile):
        return False
    user_agent = get_request().get_environ('HTTP_USER_AGENT', '')
    for bot_ua_string in [x.strip() for x in open(botfile).readlines()]:
        if bot_ua_string in user_agent:
            return True
    return False

def log(lvl, msg, session = None):
    if not logger:
        return
    if not session:
        session = get_session()
    user_id = session.user
    if not user_id:
        user_id = 'anonymous'
        if is_bot():
            user_id = 'bot'
    if user_id == 'bot' and lvl < logging.ERROR:
        return # don't log bot accesses
    address = get_request().get_environ('REMOTE_ADDR', '-')
    path = get_request().get_path()
    session_id = session.get_session_id() or '[nosession]'
    logger.log(lvl, '%s %s %s %s - %s' % (address, session_id, path, user_id, msg))

def info(msg, session = None):
    log(logging.INFO, msg, session = session)

def warn(msg, session = None):
    log(logging.WARN, msg, session = session)

def error(msg, session = None):
    log(logging.ERROR, msg, session = session)

def readline(line):
    try:
        date, hour, level, ip, session_id, url, user_id, dash, message = line.strip().split(' ', 8)
    except ValueError:
        return None # bad line in logs
    if dash != '-':
        return None
    return locals()

