from django.contrib.gis.utils import GeoIP
from django.shortcuts import render_to_response

from django.shortcuts import HttpResponse
from django.http import HttpResponsePermanentRedirect


class Geo(object):
    """
    Return GEOIP dictionary with the following keys:
    ['city', 
    'region', 
    'area_code', 
    'longitude', 
    'country_code3', 
    'latitude', 
    'postal_code', 
    'dma_code', 
    'country_code', 
    'country_name']
    """
    
    @staticmethod
    def city_from_ip(request, ip=None):
        """
        If IP is not supplied, get from request
        """
        if ip:
            city = GeoIP().city(ip)
        else:
            city = Geo.get_from_request(request)
        return HttpResponse(str(city), mimetype="text/json")
    
    @staticmethod
    def get_from_request(request):
        ip = request.META.get('REMOTE_ADDR')
        city = GeoIP().city(ip)
        return city


def redirect_if_geoip_matches(redirect_url, *geo_filters):
    """
    Checks if the request's HTTP_REFERER GEOIP matches supplied attibutes. 
    If match, then redirect to specified URL.
    """
    if not redirect_url.endswith(r'/'): redirect_url = '%s/' % redirect_url
    #if not hasattr(geo_filters, '__iter__'): geo_filters = [geo_filters]
    def _dec(view_func):
        def _check_referer(request, *args, **kwargs):
            geo = Geo.get_from_request(request)
            for geo_filter in geo_filters:
                for key, val in geo_filter.items():
                    if not geo.has_key(key): 
                        raise Exception('Invalid GEO key: %s, specified. Valid choices are : %s' % (key, geo.keys()))
                    if not geo[key] == geo_filter[key]: 
                        is_redirect = False
                        break
                    else:
                        is_redirect = True
                        break
                if is_redirect: 
                    break  # OR filter assumed
            if is_redirect:
                return HttpResponsePermanentRedirect(redirect_url)
            else:
                return view_func(request, *args, **kwargs)


********** Sample usage *******

    @redirect_if_geoip_matches('/geoip/test_redirected_from_EURO', 
                               {'country_code3': 'FRA'},
                               {'country_code3': 'DEU'},
    )
    def test_redirect_if_EURO(request):
        return HttpResponse('Not EURO')
