from base import *
from graticules import render as gratrender
from pygments.lexer import RegexLexer
from pygments.token import *
from pygments import highlight
from pygments.formatters import HtmlFormatter

def render(request, type, code=None, slug=None):
    if slug: 
        srs = get_object_or_404(SRS, type=type, slug=slug)
    else:
        srs = get_object_or_404(SRS, type=type, srs_id=code)
    try:
        b = srs.extent()

        if not b:
            raise Exception("No extent available.")
        ref = osr.SpatialReference()
        ref.ImportFromWkt(srs.wkt)
        srs = ref.ExportToProj4()
        o = gratrender.render(b,srs)
        if o == None:
            raise Exception('Mapserver is not properly installed')
        data = o.read()
    except Exception, E:
        error = {'title': 'Invalid Render Request', 'text': "Can't render that image.", 'exception': E} 
        response = render_to_response("references/404.html", error)
        return response
    response = HttpResponse()
    response.write(data)
    response['Content-length'] = str(len(data))
    response['Content-Type'] = 'image/png'
    return response


class WKTLexer(RegexLexer):
    name = 'wkt'
    aliases = ['wkt']
    filenames = ['*.wkt']

    tokens = {
        'root': [
            (r'\s+', Text),
            (r'[{}\[\]();,-.]+', Punctuation),
            (r'(PROJCS)\b', Generic.Heading),
            (r'(PARAMETER|PROJECTION|SPHEROID|DATUM|GEOGCS|AXIS)\b', Keyword),
            (r'(PRIMEM|UNIT|TOWGS84)\b', Keyword.Constant),
            (r'(AUTHORITY)\b', Name.Builtin), 
            (r'[$a-zA-Z_][a-zA-Z0-9_]*', Name.Other),
            (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
            (r'0x[0-9a-fA-F]+', Number.Hex),
            (r'[0-9]+', Number.Integer),
            (r'"(\\\\|\\"|[^"])*"', String.Double),
            (r"'(\\\\|\\'|[^'])*'", String.Single),
        ]
    }
    
def output_proj(request, ref, output, SRS, code = None, type = None):    
    response = HttpResponse()
    ct = "text/plain"
    if output.upper() =='PROJ4':
        out = ref.ExportToProj4()
    elif output.upper() == 'HTML':
        out = ref.ExportToPrettyWkt()
        pretty_wkt = highlight(out, WKTLexer(), HtmlFormatter(cssclass='syntax',nobackground=True))
        return render_to_response('references/wkt_html_view.html', {'pretty_wkt': pretty_wkt, 'srs':code})
    elif output.upper() == 'PROJ4JS':
        out = ref.ExportToProj4().strip()
        projObj = "Proj4js.defs"
        if request.GET.has_key('obj'):
            projObj = request.GET['obj']
        if code:
            out = '%s["%s:%s"] = "%s";' % (projObj, type.upper(), code, out)
    elif output.upper() == 'PRETTYWKT':
        out = ref.ExportToPrettyWkt()
    elif output.upper() == 'OGCWKT':
        out = ref.ExportToWkt()
    elif output.upper() == 'ESRIWKT':
        ref.MorphToESRI()
        out = ref.ExportToWkt()
    elif output.upper() == 'GML':
        out = ref.ExportToXML()
    elif output.upper() == 'USGS':
        out = ref.ExportToUSGS()
    elif output.upper() == 'MAPFILE':
        out = 'PROJECTION\n\t'+'\n\t'.join(['"'+l.lstrip('+')+'"' for l in ref.ExportToProj4().split()])+'\nEND' 
    elif output.upper() == 'MAPNIK': 
        proj4 = ref.ExportToProj4().strip()
        out = '<?xml version="1.0" encoding="utf-8"?>\n<Map srs="%s">\n\t<Layer srs="%s">\n\t</Layer>\n</Map>' % (proj4,proj4)
    elif output.upper() == 'MAPSERVERPYTHON':
        wkt = ref.ExportToWkt()
        out = "from mapscript import mapObj,layerObj\nwkt = '''%s'''\nm = mapObj('')\nm.setWKTProjection(wkt)\nlyr = layerObj(m)\nlyr.setWKTProjection(wkt)" % (wkt)
    elif output.upper() == 'MAPNIKPYTHON': 
        proj4 = ref.ExportToProj4().strip()
        out = "from mapnik import Map, Layer\nproj4 = '%s'\nm = Map(256,256,proj4)\nlyr = Layer('Name',proj4)" % (proj4)
    elif output.upper() == 'GEOSERVER':
        if SRS.type == 'sr-org':
          out = "# put this custom projection in the 'user_projections' file inside the GEOSERVER_DATA_DIR\n#You can further work with your projections via the web admin tool.\n%s=%s" % (code,ref.ExportToWkt())
        # we'll assume Geotools has this SRS...
        else:
          out = '<featureType datastore = "your_layer" >\n<name>your_layer</name>\n<SRS>%s</SRS>\n<!-- remainder of featuretype info-->\n</featureType>' % code
    elif output.upper() == 'POSTGIS':                                              
        out = 'INSERT into spatial_ref_sys (srid, auth_name, auth_srid, proj4text, srtext) values ( 9%s, \'%s\', %s, \'%s\', \'%s\');' % (code, type, code, ref.ExportToProj4(), ref.ExportToWkt())                                                 
    elif output.upper() == 'JSON':
        if ref.IsGeographic():
            code = ref.GetAuthorityCode("GEOGCS")
        else:
            code = ref.GetAuthorityCode("PROJCS")
        out = {}
        if code:
            out['type'] = 'EPSG'
        else:
            out['type'] = str(SRS.type)
        out['properties'] = {'code':SRS.srs_id}
        ct = "application/json" 
    elif output.upper() == 'PRJ':
        ref.MorphToESRI()
        out = ref.ExportToWkt()
        ct = "text/x-esriwkt" 
        response['Content-disposition'] = "attachment; filename=%s.prj" % code
    else:
        raise FormatError("No format found for %s" % output)
    response.write('%s' % out)
    response['Content-length'] = str(len(response.content))
    response['Content-Type'] = ct 
    return response
