#!/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 = []
  meetrondje_list_total = list()
  for user in Gebruiker.objects.all().order_by('naam'):
    entry = {'gebruiker' : user.naam}
    meetrondje_list = list()
    sum_ssid = set()
    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__organization__name__startswith='Wireless').\
        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.
      sum_ssid |= set(wirelessleiden_ssid)
      meetrondje_list.append(
        {
          'naam' : mr.naam,
          'datum' : mr.datum.strftime('%Y-%m-%d'),
          'nodes' : ['all'] + list(wirelessleiden_ssid)
        }
      )
    meetrondje_list = [{ 'naam' : 'all', 'datum' : 'any', 'nodes' : ['all'] + sorted(sum_ssid) }] + meetrondje_list
    meetrondje_list_total += meetrondje_list
    entry['meetrondje'] = meetrondje_list
    result.append(entry)
  result = [ {'gebruiker' : 'all', 'meetrondje' : meetrondje_list_total} ] + result

  # 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')
