from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.http import HttpResponse
from django.db.models import Q
from register.models import AgencyList
from register.models import Petitions
from django.templatetags.static import static

import json


@csrf_exempt
def getSignals(request):
	if request.method != 'POST':
		raise Http404('Only POSTs are allowed')

	requestJson = json.loads(request.body)
	print requestJson
	response = '{"status" : "no_such_category"}'
	if AgencyList.objects.filter(AgencyName = requestJson["agencyName"]):
		if int(requestJson["minimalId"]) == -1:
			response = getElements(requestJson["agencyName"])
		else:
			response = getElementsById(requestJson["agencyName"], requestJson["minimalId"])
	
	print response
	return HttpResponse(response, content_type='text/json')

def getElements(agencyName):
	status = '{'
	signals = 0
	minId = 0
	for index in Petitions.objects.filter(AgencyName = agencyName).order_by("-date"):
		signals +=1
		minId = index.id
		if(signals == 6):
			break
		status += '"signal' + str(signals) + '" : '
		status += '{"petitionType" : "' + index.petitionType  + '", "petitionDescription" : "' + index.petitionDescription
		status += '", "citizenName" : "' + index.citizenName + '", "citizenMiddleName" : "' + index.citizenMiddleName
		status += '", "citizenLastName" : "' + index.citizenLastName + '", "citizenAddres" : "' + index.citizenAddres
		status += '", "date" : "' + str(index.date) + '", "petition" : "' + index.petition
		status += '", "petitionData" : "' + static(index.petitionData) + '", "latitude" : "' + str(index.latitude)
		status += '", "longitude" : "' + str(index.longitude) + '"}'
		status += ', '

	if signals < 6:
		status += '"status" : "no_new_signals"}'
	else:
		status = status[:-2] #delete last comma
		status += ', "minimalId" : "' + str(minId) + '"}'

	return status


def getElementsById(agencyName,Id):
	status = '{'
	signals = 0
	minId = 0
	for index in Petitions.objects.filter(AgencyName = agencyName, id__lte= Id).order_by("-date"):
		signals +=1
		minId = index.id
		if(signals == 6):
			break
		status += '"signal' + str(signals) + '" : '
		status += '{"petitionType" : "' + index.petitionType  + '", "petitionDescription" : "' + index.petitionDescription
		status += '", "citizenName" : "' + index.citizenName + '", "citizenMiddleName" : "' + index.citizenMiddleName
		status += '", "citizenLastName" : "' + index.citizenLastName + '", "citizenAddres" : "' + index.citizenAddres
		status += '", "date" : "' + str(index.date) + '", "petition" : "' + index.petition
		status += '", "petitionData" : "' + static(index.petitionData) + '", "latitude" : "' + str(index.latitude)
		status += '", "longitude" : "' + str(index.longitude) + '"}'
		status += ', '

	if signals < 6:
		status += '"status" : "no_new_signals"}'
	else:
		status = status[:-2] #delete last comma
		status += ', "minimalId" : "' + str(minId) + '"}'

	return status