# -*- coding: utf-8 -*-
# -- mantis_tickets.py
#
# Author: Ariel Barreiro <abarrei@gmail.com>
#
# Tested with trac 0.12
# Ideas taken from: 
#  -http://trac.edgewall.org/wiki/TracDev/IWikiSyntaxProviderExample
#  -http://trac.edgewall.org/attachment/wiki/ChristianBoos/mantis_tickets.py
#  -http://trac.edgewall.org/attachment/wiki/ChristianBoos/mantis_tickets_link.py
# 
# 

"""
Support for mantis:<id> wiki syntax, it uses a configurable site setting

Please add a 
[mantis-ticket]
mantis_site = http://your_mantis_site

to your trac.ini configuration file (either global or environment specific)

This only defines a formatted link, not any other wiki syntax
"""

from genshi.builder import tag

from trac.core import *
from trac.wiki import IWikiSyntaxProvider


class MantisTicketSyntaxProvider(Component):
    """
    Support for mantis:<id> wiki syntax, it uses a configurable site setting
    """
    implements(IWikiSyntaxProvider)

    # IWikiSyntaxProvider methods

    def get_link_resolvers(self):
        """Return an iterable over (namespace, formatter) tuples.

        Each formatter should be a function of the form
        fmt(formatter, ns, target, label), and should
        return some HTML fragment.
        The `label` is already HTML escaped, whereas the `target` is not.
        """
        return [ ('mantis', self._format_mantis_link) ]

    def get_wiki_syntax(self):
        """Return an iterable that provides additional wiki syntax.

        Additional wiki syntax correspond to a pair of (regexp, cb),
        the `regexp` for the additional syntax and the callback `cb`
        which will be called if there's a match.
        That function is of the form cb(formatter, ns, match).

        We are not returning anything as we want to only allow mantis:<id> format
        """
	return []
 
    def _format_mantis_link(self, formatter, ns, target, label):
	"""Returns the formatter as plaintext if target is not an integer,
	otherwise return the proper mantis link
	"""
        mantis_site = self.config.get('mantis-ticket', 'mantis_site')
	if target.isdigit():
            return tag.a(
                "Mantis issue #%07d" % int(target), 
                href = mantis_site + '/view.php?id=' + target,
                title = "Mantis issue #%07d on %s" % (int(target), mantis_site)
            )
        else:
            return label

