from django.http import Http404, HttpResponse
from shapely.geometry import box

from c3nav.mapdata.models import Level, Source
from c3nav.mapdata.render.svg import SVGRenderer


def tile(request, level, zoom, x, y, format):
    zoom = int(zoom)
    if not (0 <= zoom <= 10):
        raise Http404

    bounds = Source.max_bounds()

    x, y = int(x), int(y)
    size = 256/2**zoom
    minx = size * x
    miny = size * (-y-1)
    maxx = minx + size
    maxy = miny + size

    if not box(bounds[0][1], bounds[0][0], bounds[1][1], bounds[1][0]).intersects(box(minx, miny, maxx, maxy)):
        raise Http404

    renderer = SVGRenderer(level, miny, minx, maxy, maxx, scale=2**zoom, user=request.user)

    try:
        renderer.check_level()
    except Level.DoesNotExist:
        raise Http404

    svg = renderer.render()

    if format == 'svg':
        response = HttpResponse(svg.get_xml(), 'image/svg+xml')
    elif format == 'png':
        response = HttpResponse(content_type='image/png')
        svg.get_png(f=response)
    else:
        raise ValueError

    return response

@@ -38,17 +38,42 @@
 Response
+, HttpResponseNotModified
 %0A
-
 from sha
@@ -137,16 +137,27 @@
 t Level,
+ MapUpdate,
  Source%0A
@@ -730,16 +730,291 @@
 .user)%0A%0A
+    update_cache_key = MapUpdate.cache_key()%0A    access_cache_key = renderer.access_cache_key%0A    etag = update_cache_key+'_'+access_cache_key%0A%0A    if_none_match = request.META.get('HTTP_IF_NONE_MATCH')%0A    if if_none_match == etag:%0A        return HttpResponseNotModified()%0A%0A
     try:
@@ -1342,16 +1342,16 @@
   else:%0A
-
         
@@ -1368,16 +1368,88 @@
 eError%0A%0A
+    response%5B'ETag'%5D = etag%0A    response%5B'Cache-Control'%5D = 'no-cache'%0A%0A
     retu

add ETag to tile renderer view