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

    This macro tries to read data about a page stored in another page.
    Sometimes, it can be useful to have one piece of data updated on multiple pages.

    The data is formatted in the source page as such:

        VariableName: Data\n

    Where "VariableName" is the name given to the data (followed by a colon':'), and where
    "Data" can be any length of text, terminated with a newline. The "Data" is obtained by
    removing the variablename, the colon, and the space seperating them. (see code below).
    Also, only one variable / data pair per line. A #format plain is generally the best
    for data pages.

    Usage: try:

        [[IncVar(WikiSandBox,storedtext)]]

    ...on any page to get "storedtext" for page "WikiSandBox", or

        [[IncVar(storedtext)]]

    ...to get "storedtext" for the "current page"/RawData or...

        [[IncVar]]

    ...to get the time the data is/was refreshed. Generally, this will be the current time.

    It will return errors if there is no stored
    data, or if a page does not exist. 

    @copyright: 2005 by Derek Wilson <sp1d3rx@gmail.com>
    @license: GNU GPL, see COPYING for details.

    Portions of this code have been taken from or inspired by Thomas Waldmann and
    Gustavo Niemeyer. Originally based off of "RandomQuote.py".

"""

import random, StringIO, time
from MoinMoin.Page import Page, wikiutil

Dependencies = ["time"]

def execute(macro, args):
    _ = macro.request.getText
    
    if args: args = args.split(',')
    #If there aren't any args, just show the date and time...
    else: return macro.formatter.text("%s" % time.strftime("%A %b %Y - %I:%M%p",time.localtime()))

    #If there's more than 1 arg, then that's a page name and a variable.
    if len(args) > 1:
        pagename = args[0]
        srchvar = args[1]
    else: #Otherwise, it's just a variable, and the pagename is implied to be "/RawData".
        srchvar = args[0]
        pagename = macro.formatter.page.page_name + "/RawData"
        
    if macro.request.user.may.read(pagename):
        page = Page(macro.request, pagename)
        raw = page.get_raw_body()
    else:
        raw = ""
    srchvar = srchvar + ':'
    lines = raw.splitlines()
    lines = [line.strip() for line in lines]
    
    if not lines:
        return (macro.formatter.highlight(1) +
                _('No variables on %(pagename)s.') % {'pagename': pagename} +
                macro.formatter.highlight(0))
    #Search for the variable in the file. Note, stops at first instance of variable.
    for line in lines:
        result = ""
        if line.startswith( srchvar + ' ' ):
            result = line.lstrip(srchvar)[1:] #strip off the space between var and data.
            break
        else:
            result = "<< data not found on that page >>"
    return macro.formatter.text("%s") % result
