#!/usr/bin/env python
# -*- coding: cp1251 -*-
"""
    Browse Wiki event-log for page requests.
    
    The macro also tries to resolve host names, if not found then host IP is given

    Usage:
        [[WikiLog(yyyy-mm-dd)]]
        where yyyy-mm-dd - day from which to start showing logs
        if no arguments given then showing for the last month

    @copyright: 2007 by Alexander "Loki" Agibalov
"""

import os, sys, socket
from MoinMoin.Page import Page
from MoinMoin.logfile import eventlog, logfile
from MoinMoin import wikiutil
from datetime import datetime

def execute(macro, args):
    request=macro.request
    _=macro.request.getText
    if not request.user.isSuperUser():
        return macro.formatter.text('Only a SuperUser can view this page!')
    if args is None:
        dNow0=datetime.now()
        if dNow0.month > 1:
            sargs=(dNow0.year, dNow0.month-1, dNow0.day)
        else:
            sargs=(dNow0.year-1, 12, dNow0.day)
        retTxt="<p><b>Page visits for the last month</b></p>"
    else:
        retTxt="<p><b>Page visits since %s</b></p>" % args
        sargs=args.split("-")
    event_log = eventlog.EventLog(request)
    try:
        logDate = event_log.date()
    except logfile.LogMissing:
        return macro.formatter.text('event log not found')
    event_log.set_filter(['VIEWPAGE'])
    sRet=retTxt
    sRet+="<table><tr><td>Date</td><td>Page</td><td>Host or IP</td><tr>"
    dHosts={}
    for event in event_log.reverse():
        date_tup=request.user.getTime(wikiutil.version2timestamp(event[0]))
        if int(date_tup[0]) < int(sargs[0]):
            break
        if (int(date_tup[0]) == int(sargs[0])) and (int(date_tup[1]) < int(sargs[1])):
            break
        if (int(date_tup[0]) == int(sargs[0])) and (int(date_tup[1]) == int(sargs[1])) and (int(date_tup[2]) <= int(sargs[2])):
            break
        sHost=str(event[2].get('REMOTE_ADDR', None))
        if not dHosts.has_key(sHost):
            try:
                lHost=socket.gethostbyaddr(sHost)
                dHosts[sHost]=lHost[0]
            except:
                dHosts[sHost]=sHost
        sHost=dHosts[sHost]
        tmpSt="<tr><td>%s</td><td>%s</td><td>%s</td></tr>" % (request.user.getFormattedDateTime(wikiutil.version2timestamp(event[0])), event[2].get('pagename', None), sHost)
        sRet+=tmpSt
    sRet+="</table>"
    return macro.formatter.rawHTML(sRet)
