# -*- coding: utf8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.db.models import Count
from django.http import HttpResponseRedirect
from main.models import Plugin, PluginPermission

from buyable.models import Purchase, Buyable, BuyableType

@login_required
def startpage(request):
	''' Diese Funktion wird wahrscheinlich viel Last erzeugen, da 
	sie ueber mehrere Tabellen joined,filtered und wieder reduced.
	'''
	drinks = BuyableType.objects.get(name="Getränk").buyable_set.all()
	snacks = BuyableType.objects.get(name="Snack").buyable_set.all()
	
	allMost = Purchase.objects.filter(isDeposit=False).values('buyable__name', 'buyable__id','buyable__image','buyable__price','buyable__deposit')
	
	allMostDrinks = allMost.filter(buyable__in=drinks).annotate(num_buys=Count('buyable')).order_by('-num_buys')
	allMostSnacks = allMost.filter(buyable__in=snacks).annotate(num_buys=Count('buyable')).order_by('-num_buys')
	
	usersMostDrinks = allMost.filter(buyable__in=drinks).filter(order__user=request.user.id).annotate(num_buys=Count('buyable')).order_by('-num_buys')
	usersMostSnacks = allMost.filter(buyable__in=snacks).filter(order__user=request.user.id).annotate(num_buys=Count('buyable')).order_by('-num_buys')
	
	usersLastDrinks = allMost.filter(buyable__in=drinks).filter(order__user=request.user.id).annotate(num_buys=Count('buyable')).order_by('-order__dateTime')
	usersLastSnacks = allMost.filter(buyable__in=snacks).filter(order__user=request.user.id).annotate(num_buys=Count('buyable')).order_by('-order__dateTime')
	
	usersLastDrinks = allMost.distinct().filter(buyable__in=drinks).filter(order__user=request.user.id).order_by('-order__dateTime')
	usersLastSnacks = allMost.distinct().filter(buyable__in=snacks).filter(order__user=request.user.id).order_by('-order__dateTime')
	
	#if someone knows a better way to do this, just replace this code
	#purpose: filter usersLast so that it only contains unique items
	#hint: distinct() does not work because dateTime is included due to order_by(), so all items appear distinct

	usersLastDrinks_unique = []
	for x in usersLastDrinks:
		if not x in usersLastDrinks_unique:
			usersLastDrinks_unique.append(x)
	#usersLastDrinks = map(lambda x:{ "buyable__name" : x }, usersLastDrinks_unique) 
	usersLastDrinks = usersLastDrinks_unique
	
	usersLastSnacks_unique = []
	for x in usersLastSnacks:
		if not x in usersLastSnacks_unique:
			usersLastSnacks_unique.append(x)
	#usersLastSnacks_unique = usersLastSnacks.distinct()
	usersLastSnacks = usersLastSnacks_unique
	
	return render_to_response("main/startpage.html", {'allMostDrinks' : allMostDrinks[:5], 'allMostSnacks' : allMostSnacks[:5], 'usersMostDrinks': usersMostDrinks[:5], 'usersMostSnacks': usersMostSnacks[:5], 'usersLastDrinks' : usersLastDrinks[:5], 'usersLastSnacks' : usersLastSnacks[:5]}, RequestContext(request))

def register(request):
	""" The "no registration available" page... """
	return render_to_response("registration/register.html", RequestContext(request))


def getPluginDict(request):
	""" Generate a dict containing the users plugin information. """
	plugins = Plugin.objects.all()
	allowed = Plugin.objects.filter(pluginpermission__user=request.user)
	unallowed = Plugin.objects.exclude(pluginpermission__user=request.user)
	perms = PluginPermission.objects.filter(user=request.user)
	
	return {'plugins': plugins, 'allowed': allowed, 'unallowed': unallowed, 'permissions': perms}

@login_required
def settings(request):
	""" Render settings page. """
	return render_to_response("settings/settings.html", getPluginDict(request), RequestContext(request))

@login_required
def pluginPermission(request, method, pluginId):
	""" View to edit the users :class:`Plugin` permissions. """
	plugin = None
	try:
		plugin = Plugin.objects.get(id=pluginId)
	except Plugin.DoesNotExist:
		d = getPluginDict(request)
		d['pluginerror'] = "Ein Plugin mit der angegebenen ID existiert nicht"
		return render_to_response("settings/settings.html", d, RequestContext(request))
	
	if method == "allow":
		try:
			p = PluginPermission.objects.get(user=request.user, plugin=plugin)
			d = getPluginDict(request)
			d['pluginerror'] = "Dieses Plugin wurde bereits erlaubt"
			return render_to_response("settings/settings.html", d, RequestContext(request))
		except PluginPermission.DoesNotExist:
			p = PluginPermission(user=request.user, plugin=plugin)
			p.save()
	else:
		try:
			p = PluginPermission.objects.get(user=request.user, plugin=plugin)
			p.delete()
		except PluginPermission.DoesNotExist:
			d = getPluginDict(request)
			d['pluginerror'] = "Keine Berechtigungen f&uuml;r dieses Plugin gefunden - kann also auch nicht zur&uuml;ckgezogen werden"
			return render_to_response("settings/settings.html", d, RequestContext(request))
	return HttpResponseRedirect("/user/settings/")

@login_required
def pluginAuthblob(request, pluginId):
	""" View to edit the users :attr:`authblob <PluginPermission.authblob>`. """
	if request.method != "POST":
		return HttpResponseRedirect("/user/settings/")
	plugin = None
	try:
		plugin = Plugin.objects.get(id=pluginId)
	except Plugin.DoesNotExist:
		d = getPluginDict(request)
		d['pluginerror'] = "Ein Plugin mit der angegebenen ID existiert nicht"
		return render_to_response("settings/settings.html", d, RequestContext(request))
	
	p = None
	try:
		p = PluginPermission.objects.get(user=request.user, plugin=plugin)
	except PluginPermission.DoesNotExist:
		d = getPluginDict(request)
		d['pluginerror'] = "Vor dem editieren vom Authblob muss das Plugin ersteinmal erlaubt werden"
		return render_to_response("settings/settings.html", d, RequestContext(request))

	if not p.plugin.userCanWriteAuthblob or not request.POST.has_key("authblob"):
		d = getPluginDict(request)
		d['pluginerror'] = "Der Authblob darf f&uuml;r dieses Plugin nicht vom User ver&auml;ndert werden (oder der Authblob war kaputt)"
		return render_to_response("settings/settings.html", d, RequestContext(request))
	
	pluginsWithAuthblob = PluginPermission.objects.filter(plugin=plugin, authblob=request.POST["authblob"])
	if p.plugin.uniqueAuthblob and pluginsWithAuthblob.count() > 0:
		d = getPluginDict(request)
		if pluginsWithAuthblob[0].user == request.user:
			d['pluginerror'] = "Das ist der gleiche Authblob, den du vorher auch hattest."
		else:
			d['pluginerror'] = "Achtung! Dein Authblob wird bereits von einer anderen Person benutzt. Bitte w&auml;hle einen anderen (eindeutigen) Authblob!"
		return render_to_response("settings/settings.html", d, RequestContext(request))
	
	p.authblob = request.POST['authblob']
	p.save()
	d = getPluginDict(request)
	d['pluginmsg'] = "Authblob erfolgreich ge&auml;ndert"
	return render_to_response("settings/settings.html", d, RequestContext(request))

