# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - Hits Macro

    PURPOSE:
        This macro is used to show the cummulative hits of the wikipage where the Macro is called from.
	Optional you could count how much a page was altered on this or all pages.

    CALLING SEQUENCE:
        [[Hits([text],[bgcolor=bgcolor],[all=(0,1)],[filter=(VIEWPAGE,SAVEPAGE)],[divid=(logo,searchform)],[noframe=(0,1)])]]

    OPTIONAL INPUTS:
        text: the text which is used as description of counter number

    KEYWORD PARAMETERS:
        bgcolor: if set to the rgb color triple this color is used. Default color is #FFFFFF
	all: if set to 1 then cummulative hits over all wiki pages is returned. Default is 0
	filter: if set to SAVEPAGE then the saved pages are counted. Default is VIEWPAGE.
	divid: if set this divid is used. Default is logo. You could use each defined in screen.css.
	       I have tried logo and searchform.
	noframe: if set to 1 only text is written without a table border. Default is 0.

    EXAMPLE:
      [[Hits]]

      [[Hits(counts)]]

      [[Hits(counts,divid=searchform)]]

      [[Hits(counts,bgcolor=#CCCCCC)]]

      [[Hits(counts,all=1)]]

      [[Hits(X pages altered,all=1,filter=SAVEPAGE)]]

    PROCEDURE:

      It must be in "MoinMoin/macro"

      Please remove the version number from the file name!

    MODIFICATION HISTORY:
        @copyright: 2004 by Reimar Bauer (R.Bauer@fz-juelich.de)
        @license: GNU GPL, see COPYING for details.
    2004-12-29 RB bug fixed eventlog is in logfile
    2005-07-15 BenjaminVrolijk exchange of filename for event-log by getPagePath
    2006-05-01 RB 1.5.3-4 bug fixed for quoting pagenames and some parts refactored


"""


from MoinMoin import wikiutil
from MoinMoin.logfile import eventlog
import os


def execute(macro,args):
    request = macro.request
    _ = request.getText
    formatter = macro.formatter
    
    kw = {} # create a dictionary for the formatter.image call
    kw["bgcolor"] = "#FFFFFF"
    kw["all"] = 0
    kw["filter"] = "VIEWPAGE"
    kw["divid"] = "logo"
    kw["noframe"] = 0

    if args:
        args = args.split(',')
        args = [arg.strip() for arg in args]
    else:
        args = []

    argc = len(args)
    kw_count = 0
    for arg in args :
        if '=' in arg:
            kw_count += 1
            key, value = arg.split('=', 1)
            kw[str(key)] = wikiutil.escape(value,quote=1)

    argc -= kw_count

    if argc == 1:
         descr = args[0]
    else:
         descr = ''

    pagename = wikiutil.quoteWikinameURL(formatter.page.page_name)
    filename = request.rootpage.getPagePath('event-log',isfile=1)
    
    file = open(filename, 'r')
    events = file.readlines()
    file.close()
    
    count = 0
    for event in events:
        try:
            line = event.rstrip()
            time, eventtype, kvpairs = line.split('\t')
        except ValueError:
                # badly formatted line in file, skip it
            continue
        if kw["filter"] and eventtype not in kw["filter"]: continue
        if kw["all"] == 0:
            if event.find(pagename+'&') > -1:
               count += 1
        else:
            count += 1

    if kw["noframe"] == 0 :
        return '<div id="%(divid)s"><table><tr><td bgcolor="%(bgcolor)s">%(count)s %(descr)s </td></tr></table></div>' % {
         "divid": kw["divid"],
         "bgcolor": kw["bgcolor"],
         "count": str(count),
         "descr": descr }
    else:
        return '<div id="%(divid)s">%(count)s %(descr)s</div>' % {
            "divid": kw["divid"],
            "count": str(count),
            "descr": descr }
       
       

    
