# -- wiki.py
#
# Author: Christian Boos <cboos@bct-technology.com>
# Date:   2005-09-26
# License: modified BSD (same as Trac)
# ----------------------------------------------------------------------------

"""Ticket links to the Mantis BTS"""

from trac.core import *
from trac.wiki import IWikiSyntaxProvider, Formatter

MANTIS_FMT = "https://your.company.com/bugtracker/view.php?id=%d"

class MantisTicketSyntaxProvider(Component):
    """Link for tickets directly go to mantis BTS."""

    implements(IWikiSyntaxProvider)

    def get_link_resolvers(self):
        return [('bug', self._format_link),
                ('ticket', self._format_link),
                ('mantis', self._format_link)]

    def get_wiki_syntax(self):
        yield (
            # matches #... but not &#... (HTML entity)
            r"!?(?<!&)#"
            # optional intertrac shorthand #T... + digits
            r"(?P<it_mantis>%s)\d+" % Formatter.INTERTRAC_SCHEME,
            lambda x, y, z: self._format_link(x, 'mantis', y[1:], y, z))

    def _format_link(self, formatter, ns, target, label, fullmatch=None):
        intertrac = formatter.shorthand_intertrac_helper(ns, target, label,
                                                         fullmatch)
        if intertrac:
            return intertrac
        try:
            number = int(target)
            href = MANTIS_FMT % number
            text = target == label and "#%07d" % number or label
            return formatter._make_ext_link(href, text, 'Mantis Bug ' + text)
        except ValueError:
            return label

