# 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 models import Buyable, BuyableType, Purchase, Order
from django.contrib import admin
from django import forms
from PIL import Image
from django.core.files.uploadedfile import InMemoryUploadedFile

class BuyableAdminForm(forms.ModelForm):
	""" Special BuyableAdminForm which checks the buyable image for an 1:1 aspect ratio. """
	class Meta:
		model = Buyable
	
	def clean_image(self):
		img = self.cleaned_data['image']
		width, height = (0, 0)
		if isinstance(img, InMemoryUploadedFile):
			i = Image.open(img)
			width, height = i.size
		else:
			width, height = img.width, img.height

		if width != height:
			raise forms.ValidationError("Aspect ratio of image should be 1:1 (width x height was (%dx%d))"% (width, height))
		return self.cleaned_data['image']

class BuyableAdmin(admin.ModelAdmin):
	form = BuyableAdminForm
	list_display = ('name','price','deposit','types')
	list_filter = ['buyableType']
	search_fields = ['name','description']
	

class BuyableTypeAdmin(admin.ModelAdmin):
	list_display = ('name','itemcount')

class PurchaseInline(admin.TabularInline):
	model = Purchase
	fields = ('buyable','isDeposit','price')

class OrderAdmin(admin.ModelAdmin):
	list_display = ('user','price','dateTime','itemList')
	list_filter = ['user']
	search_fields = ['user__username','user__first_name','user__last_name']
	date_hierarchy = 'dateTime'
	ordering = ['-dateTime']

	inlines = [PurchaseInline,]

admin.site.register(Buyable, BuyableAdmin)
admin.site.register(BuyableType, BuyableTypeAdmin)
#admin.site.register(Purchase) included in Order administration page
admin.site.register(Order, OrderAdmin)

