# -*- coding: utf-8 -*-
"""
    MoinMoin - VarStr

    Set and Get variable strings in current wiki documents.

    @copyright: 2006 by Gouichi Iisaka < iisaka51 at hotmail dot com >
    @license: GNU GPL
"""

from MoinMoin import config
from MoinMoin.parser import wiki

_ErrVar = 0
_GetVar = 1
_SetVar = 2

# VarStr macro cannot be cached
Dependencies = ["time"]

def parse_args(args): 
    if len(args) == 0:
        return _ErrVar, '', ''

    pos = args.find('=')
    if pos < 0:
        return _GetVar, '', args
    elif pos == 0:
        return _ErrVar, '', ''
    else:
        return _SetVar, args[:pos], args[pos+1:]

def execute(macro, args):
    # create storage for variable string
    if not hasattr(macro.request, 'varbuffer'):
        macro.request.varbuffer = {}

    op, tag, val = parse_args(args)
    # nothing to do 
    if op == _GetVar:
        if macro.request.varbuffer.has_key(val):
            return macro.formatter.text(macro.request.varbuffer[val])
        else:
            return macro.formatter.text("VarStr:Keyword Error: %s" % val)
    elif op == _SetVar:
        macro.request.varbuffer[tag]=val
        return ''
    else:
        return macro.formatter.text("VarStr:Syntax Error:%s" % args)
