#!/usr/bin/env python
#
# View serving filter values.

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

def serve_filters(request):
  """Example json input for dynamic filter using multiple objects example:
  http://lijst.wirelessleiden.nl/pipermail/techniek/2011-May/005516.html"""
  result = list()
  for user in Gebruiker.objects.all().order_by('naam'):
    entry = {'gebruiker' : user.naam}
    meetrondje_list = list()
    for mr in MeetRondje.objects.filter(gebruiker=user).order_by('naam'):
      # Get list if accespoints found in the specific 'Meting', and make this is list.
      wirelessleiden_ssid = Meting.objects.filter(meetrondje=mr,
        accespoint__ssid__contains='WirelessLeiden').\
        values_list('accespoint__ssid',flat=True).\
        order_by('accespoint__ssid').distinct()
      # The explicit cast to list is required as django lists are special and
      # cannot be handled by simplejson.
      meetrondje_list.append(
        {
          'naam' : mr.naam,
          'datum' : mr.datum.strftime('%Y-%m-%d'),
          'nodes' : list(wirelessleiden_ssid)
        }
      )
    entry['meetrondje'] = meetrondje_list
    result.append(entry)

  # Pretty formatting, makes debugging the json responses more easy
  json_response = simplejson.dumps(result,indent=2*' ')
  return HttpResponse(json_response, content_type='application/javascript; charset=utf8')
