"""
    MoinMoin - PageHits Macro

    Copyright (c) 2002 by Thomas Waldmann <ThomasWaldmann@gmx.de>
    All rights reserved, see COPYING for details.

    Revision history:
    0.xx first version without a number
    0.2  do not display non-existing pages
"""

# Imports
import string
from MoinMoin import config, wikiutil
from MoinMoin.Page import Page
#from MoinMoin.i18n import _


def execute(macro, args):
    data = macro.request.getEventLogger().read(['VIEWPAGE'])
    pagehits={}
    for event in data:
        page = event[2]['pagename']
        try:
            pagehits[page]=pagehits[page]+1
        except:
            pagehits[page]=1

    # get hits and sort them
    hits = []
    for pagehit in pagehits.items():
        if Page(pagehit[0]).exists():
            hits.append((pagehit[1],pagehit[0]))
    hits.sort()
    hits.reverse()

    # format list
    result = macro.formatter.number_list(1)
    for hit, page in hits:
        result = (result + macro.formatter.listitem(1) +
            macro.formatter.code(1) + 
            string.replace("%6d" % hit, " ", "&nbsp;") + " " +
            macro.formatter.code(0) + 
            macro.formatter.pagelink(page) + 
            macro.formatter.listitem(0)
        )
    result = result + macro.formatter.number_list(0)

    return result
#    , 0

