#
# GeoIP template tags
# Rachel Willmer Oct 2006
# rachel at hobthross dot com 
#

from django import template
import re
import GeoIP

register = template.Library()

#
# Templatetag get_country_name returns the client's country code
#
# Example: 
# {% ifequal get_country "GB" %}
# 	do something
# {% endifequal %}
#
class CountryNameNode(template.Node):

    def __init__(self):
        pass

    def render(self, context):
        gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
        country=gi.country_code_by_addr(context['remote_addr'])
        if country==None:
            country="Not Known"
        return country

@register.tag
def get_country_name(parser,token):
    return CountryNameNode()


####

#
# Templatetag get_country sets the given variable name 
# to the client's country code 
#
# Example: 
# {% get_country as my_country %}
# {% ifequal my_country "GB" %}
# 	do something
# {% endifequal %}
#
class CountryNode(template.Node):

    def __init__(self, var_name):
        self.var_name=var_name

    def render(self, context):
        gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
        country=gi.country_code_by_addr(context['remote_addr'])
        if country==None:
            country="Not Known"
        context[self.var_name]=country
        return ''

@register.tag
def get_country(parser,token):
    try:
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires a var name" % token.contents[0]

    m=re.search(r'(as) (\w+)', arg)
    if not m:
        raise template.TemplateSyntaxError, "%r tag had invalid arguments (%r)" % (tag_name,arg)

    var_name=m.group(2)
    return CountryNode(var_name)

# end of file
