# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse

import datetime
from buyable.models import Buyable, Purchase, Order
from django.core import serializers


@login_required
def showItems(request):
	# FIXME: Implement pagination here
	items = Buyable.objects.all()
	
	#return json-container
	container = serializers.serialize('json', items)
	return HttpResponse(container,'application/json')

@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 HttpResponse(status=400)
		
	#return json-container
	container = serializers.serialize('json', [item])
	return HttpResponse(container,'application/json')


@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)
	# TANNEK! if buymode == "with/dopsit" or buymode == "only/deposit":
	if buymode == "with/deposit" or buymode == "only/deposit":
		p = Purchase(order=order, buyable=item, isDeposit=True)
		p.save(saveOrder=False)
	order.save()
	
	#return json-container
	#container = serializers.serialize('json', items)
	#return HttpResponse(container,'application/json')
	return HttpResponse(status=200)
	#return HttpResponseRedirect("/store/bought/%s/" % (order.id)) 

@login_required
def history(request):
	hist = Order.objects.filter(user=request.user.id).order_by("-dateTime")
	#return json-container
	container = serializers.serialize('json', [hist])
	return HttpResponse(container,'application/json')

