﻿# -*- coding: utf-8 -*-
"""
MoinMoin - Link macro

This macro create localized links with extra html attributes. This could
be useful to add access keys to your main wiki pages for better
usability and accessability.
    
Creating a link to localized page:
    
    [[Link(FrontPage)]]
        
Same with accesskey:
    
    [[Link(FrontPage, accesskey="1")]]
        
Same with special class:
    
    [[Link(FrontPage, accesskey="1" class="special")]]
    
    The second argument is rendered as is in the a tag. You can add any
    html attribtues in any order.

@copyright: 2005 by Nir Soffer <nirs@freeshell.org>
@license: GNU GPL, see COPYING for details.
"""

Dependencies = ["language", "namespace"]

class Link:
    """ Localized link with html attributes """

    arguments = ['name', 'attributes']

    def __init__(self, macro, args):
        self.macro = macro
        self.request = macro.request
        self.args = self.parseArgs(args)

    def parseArgs(self, string):
        """ Temporary function until Oliver Graf args parser is finished

        @param string: string from the wiki markup [[NewPage(string)]]
        @rtype: dict
        @return: dictionary with macro options
        """
        if not string:
            return {}
        args = [s.strip() for s in string.split(',')]
        args = dict(zip(self.arguments, args))
        return args

    def errors(self):
        """ Validate arguments and return error message

        @rtype: unicode
        @return: error message for bad argument, or None if ok.
        """
        _ = self.request.getText
        
        # Must have non empty page name
        if not self.args.get('name'):
            error = _('Missing page name.')
            # Should use abstract formatter.wikiMarkupError() call,
            # but there is no such call, so just use html.
            return u'<span class="error">%s</span>' % error
        
        return None
        
    def name(self):
        """ Return localized name safe for rendering """
        name = self.args['name']
        localized = self.macro.request.getText(name, formatted=False)
    
        # If we got same text, it means there was no translation, and this
        # is unsafe user text that must be escaped.
        if name == localized:
            localized = self.macro.formatter.text(localized)
            
        return localized

    def attributes(self):
        """ Return optional link attributes, safe for rendering """
        attributes = self.args.get('attributes', u'')
        if attributes:
            attributes = self.macro.formatter.text(attributes)

        return attributes
 
    def renderInText(self):
        """ Render macro in paragraph context

        The parser should decide what to do if this macro is placed in a
        page context.
        
        @rtype: unicode
        @return rendered output
        """
        errors = self.errors()
        if errors:
            return errors

        attributes = self.attributes()
        name = self.name()
        
        # TODO: should use the formatter to create output that works on
        # any format, but formatter.url ignore 'attrs' keyword sent by
        # wikiutil.link_tag. Untill it is fixed, use duplicate code that
        # mostly works.
        # Note: this page link will not be cached.
        from MoinMoin.Page import Page
        if not Page(self.request, name).exists():
            attributes += ' class="nonexistent"'
        
        out = u'<a href="%(script)s/%(name)s"%(attr)s>%(name)s</a>' % {
            'attr': attributes, 
            'script': self.request.getScriptname(), 
            'name': name,
            }        
        return out

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