# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - extAction macro
    
    Creates an action link.

    Usage:

        [[Action("action")]]
        Create a link to current page with '?action=action' and the
        translated link text 'action'.

        [[Action("action", "text")]]
        Same with custom 'text' as link text.

        [[Action("action", page="pagename")]]
        Create a link to the page 'pagename' with '?action=action' and the
        translated link text 'pagename[action]'.

        [[Action("action", "text", "pagename")]]
        Same with custom 'text' as link text.

    Please note: Except for "Edit" and "Slideshow" translations for the
    built-in actions are missing in Moin currently.

    @copyright: 2004-2007 by Johannes Berg <johannes@sipsolutions.de>
                and Oliver Siemoneit <oliver.siemoneit@web.de>
    @license: GNU GPL, see COPYING for details.
"""

from MoinMoin import wikiutil
from MoinMoin.Page import Page

Dependencies = ["language"]

class ActionLink:
    """ ActionLink - link to page with action """

    def __init__(self, macro, args):
        self.macro = macro
        self.request = macro.request
        argParser = wikiutil.ParameterParser("%(action)s%(text)s%(page)s")
        # Prevent argParser from crashing when macro was called with '[[Action]]' only
        if not args:
            args='""'
        self.arg_list, self.arg_dict = argParser.parse_parameters(args)
        
    def renderInText(self):
        """ Render macro in text context

        The parser should decide what to do if this macro is placed in a
        paragraph context.
        """
        _ = self.request.getText

        # Default to 'show page' instead of an error message (too lazy to
        # do an error message now).
        action = self.arg_dict['action']
        if not action:
            action = 'show'
        action = wikiutil.escape(action, 1)

        # Basepage for action
        page = self.arg_dict['page']

        # Use text (or translated action name instead) as link text 
        text = self.arg_dict['text']
        if not text:
            text = _(action, formatted=False)
            if page:
                text = '%s [%s]' % (page, text)
        text = wikiutil.escape(text, 1)

        # Create link
        target = self.macro.formatter.page
        if page:
            target = Page(self.request, wikiutil.escape(page, 1))
        link = target.link_to(self.request, text, querystr='action=%s' % action)
        return link


def execute(macro, args):
    """ Temporary glue code to use with moin current macro system """
    return ActionLink(macro, args).renderInText()


