from urllib import urlencode, quote as urlquote, unquote
from django import template
from main.templatetags import pgp

register = template.Library()


def link_encode(url, query):
    # massage the data into all utf-8 encoded strings first, so urlencode
    # doesn't barf at the data we pass it
    query = {k: unicode(v).encode('utf-8') for k, v in query.items()}
    data = urlencode(query)
    return "%s?%s" % (url, data)


@register.inclusion_tag('packages/details_link.html')
def details_link(pkg):
    return {'pkg': pkg}


@register.simple_tag
def scm_link(package, operation):
    parts = ("abslibre", operation, package.repo.name.lower(), package.pkgbase)
    linkbase = (
        "https://projects.parabola.nu/%s.git/%s/%s/%s")
    return linkbase % tuple(urlquote(part.encode('utf-8')) for part in parts)


@register.simple_tag
def bugs_list(package):
    if package.arch.name == 'mips64el':
        project = "mips64el"
    else:
        project = "issue-tracker"
    url = "https://labs.parabola.nu/projects/%s/search" % project
    data = {
        'titles_only': '1',
        'issues': '1',
        'q': package.pkgname,
    }
    return link_encode(url, data)


@register.simple_tag
def bug_report(package):
    url = "https://labs.parabola.nu/projects/"
    if package.arch.name == 'mips64el':
        url = url + "mips64el/issues/new"
    else:
        url = url + "issue-tracker/issues/new"
    data = {
        'issue[subject]': '[%s] PLEASE ENTER SUMMARY' % package.pkgname,
    }
    return link_encode(url, data)

@register.simple_tag
def flag_unfree(package):
    url = "https://labs.parabola.nu/projects/"
    if package.arch.name == 'mips64el':
        url = url + "mips64el/issues/new"
    else:
        url = url + "issue-tracker/issues/new"
    data = {
        'issue[tracker_id]': '4', # "freedom issue"
        'issue[priority_id]': '1', # "freedom issue"
        'issue[watcher_user_ids][]': '62', # "dev-list"
        'issue[subject]': '[%s] Please put your reasons here (register first if you haven\'t)' % package.pkgname,
    }
    return link_encode(url, data)


@register.simple_tag
def wiki_link(package):
    url = "https://wiki.parabola.nu/index.php"
    data = {
        'title': "Special:Search",
        'search': package.pkgname,
    }
    return link_encode(url, data)


@register.simple_tag
def pgp_key_link(key_id, link_text=None):
    return pgp.pgp_key_link(key_id, link_text)


@register.filter
def url_unquote(original_url):
    try:
        url = original_url
        if isinstance(url, unicode):
            url = url.encode('ascii')
        url = unquote(url).decode('utf-8')
        return url
    except UnicodeError:
        return original_url

# vim: set ts=4 sw=4 et:
