# -*- 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 "". 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,noframe=0)]]

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

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

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

       Now we have [[Hits]] hits on this page.


    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 1.5.3-4 RB bug fixed for quoting pagenames and some parts refactored
    2006-05-02 1.5.3-5 RB bug fixed quoting changed to url_quote_plus because of the '+' sign used for a blank 
               in a Wiki Name instead of the '_' in the log file
               
    2006-05-04 1.5.3-6 RB: divid is by now on default "" 
                           if no keyword is used only the value is returned and could be used 
                           in normal text


"""


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"] = ""
    kw["noframe"] = "1"

    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)
    pagename = wikiutil.url_quote_plus(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["divid"] == "" and  kw["noframe"] == "1":   
        return "%s %s" % (str(count),descr)     
    
    elif 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 }
    elif kw["noframe"] == "1" :
        return '<div id="%(divid)s">%(count)s %(descr)s</div>' % {
            "divid": kw["divid"],
            "count": str(count),
            "descr": descr }
       
       

    
