# -*- 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 this page was changed. It could be used to show all page interactions too.

    CALLING SEQUENCE:
        [[Hits([all=(0,1)],[filter=(VIEWPAGE,SAVEPAGE)]]

    KEYWORD PARAMETERS:
        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.

    EXAMPLE:
       [[Hits]]

       [[Hits(all=1)]]

       [[Hits(all=1,filter=SAVEPAGE)]]

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

       Or you can use the Frame parser to use alignment and others
       {{{#!Frame align=float:right,background=#efefef
       [[Hits]] hits
       }}}

      {{{#!Frame align=clear
      }}}
    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 "" 
                           noframe is default 1
                           if no keyword is used only the value is returned and could be used 
                           in normal text
                           
    2006-05-05 1.5.3-7 RB:bug fixed only pagenames should be counted
    2006-08-16 1.6.0-8 RB:PEP8 and  
                       removed all Keyword Parameters which could be used by the Frame parser 
                       or the wiki markup itselfs
                       

"""


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

Dependencies = ['time'] # do not cache

def execute(macro, args):
    request = macro.request
    _ = request.getText
    formatter = macro.formatter

    kw = {} # create a dictionary for the formatter.image call
    kw["all"] = "0"
    kw["filter"] = "VIEWPAGE"

    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
    #pagename = wikiutil.quoteWikinameURL(formatter.page.page_name)
    pagename = wikiutil.url_quote_plus(formatter.page.page_name)
    thispage_name = "pagename=%s&" % (pagename)
    
    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 line.find(thispage_name) > -1:
               count += 1
        else:
            count += 1

    return "%s" % str(count)

