# -*- encoding: utf-8 -*-

from django.core.urlresolvers import reverse
from django.db import connection
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render

from mymontools.paginate import paginate

from .models import *
from .forms import *
from .tools import nagtrap_get_filtered_traps_for_querydict

from pprint import pprint

# Paginator
##############################################################################

def nagtrap_index(Request):
	env = {}

	page = Request.GET.get('page')
	pprint( Request.GET )
	traps = nagtrap_get_filtered_traps_for_querydict(Request.GET)
	env['traps'] = paginate(traps, page, 50)
	env['trapcount'] = traps.count()

	nsf = NagtrapSimpleFilter(Request.GET)
	nsf.fields['hostname'].choices = [ (x, x) for x in Snmptt.objects.exclude(hostname='').values_list('hostname', flat=True).order_by('hostname').distinct() ]
	nsf.fields['eventid'].choices = [ (eventid, trapoid) for eventid, trapoid in Snmptt.objects.exclude(trapoid='').values_list('eventid', 'trapoid').order_by('trapoid').distinct() ]
	nsf.fields['severity'].choices = [ (x, x) for x in Snmptt.objects.exclude(severity='').values_list('severity', flat=True).order_by('severity').distinct() ]
	nsf.fields['category'].choices = [ (x, x) for x in Snmptt.objects.exclude(category='').values_list('category', flat=True).order_by('category').distinct() ]
	nsf.fields['trapread'].choices = [ ('False', 'Unread'), ('True', 'Read') ]
	env['nagtrapfilter'] = nsf

	nse = NagtrapSimpleExclude(Request.GET)
	env['nagtrapexclude'] = nse
	for field in nsf.fields.keys():
		nse.fields[u'exclude_%s' % field].choices = nsf.fields[field].choices

	return render(Request, 'nagtrap/nagtrap_index.html', env)



def nagtrap_modify(Request):
	action = Request.POST.get('action') or Request.GET.get('action')
	trapID = Request.GET.get('trapID')
	trapIDs= Request.POST.getlist('trapIDs')

	# FIXME:#45 'archive']:
	if not action in ['read', 'delete', ]:
		return HttpResponse(u'Action "%s" not implemented' % action )

	if trapID:
		trapIDs.append(trapID)

	if action == 'read':
		Snmptt.objects.filter(id__in=trapIDs).update(trapread=True)
	elif action == 'delete':
		Snmptt.objects.filter(id__in=trapIDs).delete()

	params = Request.GET.copy()
	if 'action' in params:
		params.pop('action')
	if trapID in params:
		params.pop('trapID')
	return HttpResponseRedirect( reverse('nagtrap_index') + '?%s' % params.urlencode() )



def nagtrap_search(Request, searchtype=None):
	f = {}
	f[searchtype+'__contains'] = Request.POST.get('q') or Request.GET.get('q')
	results = [ value[searchtype] for value in Snmptt.objects.filter(**f).order_by(searchtype).values(searchtype).distinct() ]
	return render(Request, 'search.html', {'results': results,})