#!/usr/bin/env python
#
# View serving filter values.
#
# Dennis Wagenaar
# d.wagenaar@gmail.com

from django.core.management import setup_environ
from django.db.models import Max
from django.http import HttpResponse
from django.core import serializers
from gheat.models import *
from gheat import gmerc
import logging
import pygame
import sys
import tempfile
import simplejson


# todo: Create one single json file with all relevent info needed for filters.  datum - meetrondje - gebruiker
def serve_filter(request, ftype):
  filterlist = ''
  if (ftype == 'filter_node'):
    filterlist = get_node()
  elif (ftype == 'filter_user'):
    filterlist = get_user()
  elif (ftype == 'filter_dataset'):
    filterlist = get_dataset()
  else:
    print 'Invalid filter'
  
  return HttpResponse(filterlist, content_type = 'application/javascript; charset=utf8')


def get_node():

  nodes = Accespoint.objects.filter(ssid__contains='WirelessLeiden').distinct()
  nodelist = serializers.serialize('json', nodes, fields=('ssid'))
  return nodelist


def get_user():

  users = Gebruiker.objects.all()
  userlist = serializers.serialize('json', users, fields=('naam'))
  return userlist


def get_dataset():

  datasets = MeetRondje.objects.all()
  datasetlist = serializers.serialize('json', datasets, fields=('naam', 'gebruiker'))
  return datasetlist


def foo_filter(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,
          'date' : 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')
