"""
    MoinMoin - Quote Macro
    
    This macro allows to insert a html <q cite=".." lang="...">Your quote </q>
    element.

    Usage:
       [[Quote("Your quote as long as you want")]]
       [[Quote("Your quote, more, more...", cite=http://source.net, language=en)]]
       [[Quote("Your quote, more, more...", cite=http://source.net, footnote=0)]]

    Please note: If a cite source is provided, by default a footnote is created. You
    can turn this behaviour of by seeting "footnote=0".

    For longer quotes please use the quote parser which outputs text inside a html
    <blockquote> ... </blockquote> element.

    @copyright: 2007 Oliver Siemoneit
    @license: GNU GPL, see COPYING for details.

"""

from MoinMoin import wikiutil, i18n
from MoinMoin.macro.FootNote import execute as make_footnote


def _getArgs(given_arguments, allowed_arguments):
    if not given_arguments:
        return {}
    args = {}
    for s in given_arguments.split(','):
        if s and s.find('=') > 0:
            key, value = s.split('=', 1)
            if key and value:
                key = key.strip()
                if key in allowed_arguments:
                    args[key] = value.strip()
    return args

def _get_formatterName(formatter):
    # XXX remove this function again. It's just a workaround since FormatterBase
    # has no 'def quote' yet.
    import inspect
    for key, value in inspect.getmembers(formatter, inspect.isclass(formatter)):
        if key == '__module__':
            return value
    return ''

def execute(macro, options):
    allowed_args = ['cite', 'language', 'footnote']
    # parse given options
    try:
        text, given_args = options.rsplit('"', 1)
    except:
        return
    text = text.strip('"')
    args = _getArgs(given_args, allowed_args)

    # get cite source
    source = args.get('cite', None)
    footnote = int(args.get('footnote', '1'))
    cite = fn = ''
    if source:
        cite = ' cite="%s"' % wikiutil.escape(source)
        if footnote:
            fn = make_footnote(macro, wikiutil.escape(source))
    # get language
    language = args.get('language', None)
    lang = ''
    if language and (language in i18n.wikiLanguages()):
        lang = ' lang="%s"' % language

    # ouput quote
    # XXX change that in a "macro.formatter.quote" call
    if _get_formatterName(macro.formatter) == 'MoinMoin.formatter.text_html':
        output = '<q %s%s>' % (cite, lang) + text + '</q>' + fn
    else:
        ouput = macro.formatter.text(text) + fn
    return output

