#!/usr/bin/env python
#
# View serving available WirelessLeiden Nodes in list on mouseover.
#
# Dennis Wagenaar
# d.wagenaar@gmail.com

from django.core.management import setup_environ
from django.http import HttpResponse
from django.core import serializers
from gheat.models import *
from gheat import gmerc

def get_bounds(zoom,lat,lon):

  # Getting max radius for zoomlevel. Note that it will make a square using this, not a circle.
  SIZE = 250
  tile_height = float(40008000) / (2 ** zoom)
  meters_per_pixel = float(tile_height) / SIZE
  radius = 150 / meters_per_pixel

  # Getting pixel location for mouseposition
  mouse_x, mouse_y = gmerc.ll2px(lat,lon,zoom)
  
  max_x = int(mouse_x + radius)
  max_y = int(mouse_y + radius)
  min_x = int(mouse_x - radius)
  min_y = int(mouse_y - radius)

  max_lat, max_lon = gmerc.px2ll(max_x, min_y, zoom)
  min_lat, min_lon = gmerc.px2ll(min_x, max_y, zoom)

  return (max_lat, max_lon, min_lat, min_lon)


def make_list(zoom,lat,lon):

  maxlat, maxlon, minlat, minlon = get_bounds(zoom,lat,lon)

  filter = {}
  filter.update({
    'ssid__contains' : 'WirelessLeiden',
    'meting__latitude__lt' : maxlat,
    'meting__longitude__lt' : maxlon,
    'meting__latitude__gt' : minlat,
    'meting__longitude__gt' : minlon
  })

  objquery = Accespoint.objects.filter(**filter).distinct()
  nodelist = serializers.serialize('json', objquery, fields=('fields','ssid'))

  return nodelist


def serve_nodelist(request,zoom,lat,lon,):
  nodelist = make_list(int(zoom), float(lat), float(lon))
  return HttpResponse(nodelist, content_type = 'application/javascript; charset=utf8')
