#!/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()
  all_ssids = set()
  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 accesspoints found in the specific 'Meting', and make this is list.
      wirelessleiden_ssid = Meting.objects.filter(meetrondje=mr,
        accesspoint__organization__name__startswith='Wireless').\
        values_list('accesspoint__ssid',flat=True).\
        order_by('accesspoint__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)
        }
      )

    # Hack to gather totals, used for the ``all'' filter
    meetrondje_list_total += meetrondje_list
    all_ssids |= sum_ssid

    meetrondje_list = [{ 'naam' : 'all', 'datum' : 'any', 'nodes' : ['all'] + sorted(sum_ssid) }] + meetrondje_list
    entry['meetrondje'] = meetrondje_list
    result.append(entry)

  # Hack the ``all'' user filter in the results
  meetrondje_list_total = [{'naam' : 'all', 'datum' : 'any', 'nodes' : ['all'] + sorted(all_ssids)}] + sorted(meetrondje_list_total, key=lambda x: x['naam'])
  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')
