# -*- coding: utf-8 -*-
# This file is part of k4ever, a point-of-sale system
#   Contact............  <k4ever@lists.someserver.de>
#   Website............  http://k4ever.someserver.de/
#   Bug tracker........  http://k4ever.someserver.de/report
#
# Licensed under GNU Affero General Public License v3 or later

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
import datetime
from models import Buyable, Purchase, Order
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger, InvalidPage

@login_required
def showItems(request):
	# FIXME: Implement pagination here
	items = Buyable.objects.all()
		
	try:
		order_by = request.GET.get('order', 'date')
	except ValueError:
		order_by = 'date'
	
	if order_by == 'alphabet':
		items = items.order_by('name')
	if order_by == 'price':
		items = items.order_by('price')
	
	return render_to_response("buyables/showItems.html", {'items': items}, RequestContext(request))

@login_required
def showItem(request, itemid):
	try:
		item = Buyable.objects.get(id=itemid)
	except Buyable.DoesNotExist:
		# baww, kein item mit der id :( (oder mutax trollt rum)
		return HttpResponseRedirect("/buy/")
	return render_to_response("buyables/showItem.html", {'item': item}, RequestContext(request))


@login_required
def buyItem(request, itemid, buymode=""):
	user = request.user
	try:
		item = Buyable.objects.get(id=itemid)
	except Buyable.DoesNotExist:
		# oh no! kein item mit der id :( mutax trollt rum)
		return HttpResponseRedirect("/store/buy/")
	""" tristate variable buymode:
			""              only item
			"with/deposit"  item and deposit
			"only/deposit"  only deposit
	"""
	order = Order(user=request.user)
	order.save() # for the id!
	if buymode == "" or buymode == "with/deposit":
		p = Purchase(order=order, buyable=item, isDeposit=False)
		p.save(saveOrder=False)
	if buymode == "with/deposit" or buymode == "only/deposit":
		p = Purchase(order=order, buyable=item, isDeposit=True)
		p.save(saveOrder=False)
	order.save()
	return HttpResponseRedirect("/store/bought/%s/" % (order.id)) 

@login_required
def boughtItem(request, orderid):
	""" View which shows what was bought."""
	error = None
	try:
		item = Order.objects.get(id=orderid)
	except Order.DoesNotExist:
		error = "Die angegebene Order existiert nicht"
	if error == None and (item.user != request.user):
		item1 = None
		error = u"Diese Items gehören dir nicht"
	return render_to_response("buyables/itemBought.html", {'order': item, 'error': error}, RequestContext(request))

@login_required
def history(request):
	""" Show the users previous orders. """
	hist = Order.objects.filter(user=request.user.id).order_by("-dateTime")
	paginator = Paginator(hist, 10, orphans=3)
	
	try:
		pagenum = request.GET.get('page', 1)
	except ValueError:
		pagenum = 1

	try:
		histpage = paginator.page(pagenum)
	except PageNotAnInteger:
		# If page is not an integer, deliver first page
		histpage = paginator.page(1)
	except (EmptyPage, InvalidPage):
		# If page is out of range, deliver last page
		histpage = paginator.page(paginator.num_pages)

	return render_to_response("buyables/history.html", {'history': histpage}, RequestContext(request))
