from base import *
from srsbrowser.models import SRS
from django.utils import simplejson

from osgeo import osr, ogr

def projection(request):

    try:
        outref = request.GET.get("outref", "EPSG:4326")
        (type, code) = outref.split(":")
        srs = SRS.objects.get(type=type.lower(), srs_id=code)
        outref = osr.SpatialReference(str(srs.wkt))
    except KeyError:
        outref = osr.SpatialReference();
        outref.ImportFromEPSG(4326)

    try:
        inref = request.GET.get("inref", "EPSG:4326")
        (type, code) = inref.split(":")
        srs = SRS.objects.get(type=type.lower(), srs_id=code)
        inref = osr.SpatialReference(str(srs.wkt))
    except KeyError:
        inref = osr.SpatialReference();
        inref.ImportFromEPSG(4326)
        
    try:
        callback = request.GET['callback']
    except KeyError:
        callback = None
    try:
        json = request.REQUEST['json']
    except KeyError:
        json = None    
    
    try:
        url = request.GET['url']
    except KeyError:
        url = None
    
    if json == None and url:    
        url = url.replace('"', '')
        url = url.split(':')[1]
        url = urllib.quote(url)
        url = 'http:'+url
        json = urllib2.urlopen(url).read()

    try:
        j = simplejson.loads(json)
        x = j['geometry']
        ct = osr.CoordinateTransformation(inref, outref)
        geometry = ogr.CreateGeometryFromJson(simplejson.dumps(x))
        geometry.Transform(ct)
        return JSONResponse(geometry.ExportToJson(), callback=callback)

    except Exception, E:
        return JSONResponse({'error':str(E)}, callback=callback)
    else:
        raise Http404
