from django import template
import re
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from django.urls import reverse
from members.models import Member, Job

register = template.Library()


@register.filter(is_safe=True)
@stringfilter
def tags_to_url(value):
    # return "Tag to url: %s" % value
    return mark_safe(re.sub(r'\#([\d\w-]+)', r'<a href="/posts/t/\g<1>">#\g<1></a>', value))


def create_a_link_for(v):
    v = v.group(1)
    try:
        m = Member.all_members.get(nickname=v)
        str_nickname = str(reverse('member', kwargs={"member_name": m.nickname}))
        return '<a href="' + str_nickname + '">' + v + "</a>"
    except Exception:
        m = None
    try:
        j = Job.objects.filter(shortterm=v).first
        if j:
            return '<a href="' + '"' > + j.name + '</a>'
    except Exception:
        j = None

    return "<a href=\"/posts/%s\">%s</a>" % (v, v)


@register.filter(is_safe=True)
def add_internal_links(value):
    # m=Member.all_members.get(value)

    return mark_safe(re.sub(r'\[\[([\d\w-]+)\]\]', create_a_link_for, value))
