# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
import datetime
from decimal import Decimal

# Create your models here.
class BuyableType(models.Model):
	""" Type/Category for a buyable object """
	name = models.CharField(max_length=100)
	
	def __unicode__(self):
		return self.name


class Buyable(models.Model):
	""" Represents a buyable item. """
	name = models.CharField(max_length=100)
	price = models.DecimalField(max_digits=8, decimal_places=2)
	image = models.ImageField(upload_to='img/buyable/', help_text="<strong>The Image needs to have a 1:1 aspect ratio.</strong>")
	deposit = models.DecimalField(max_digits=8, decimal_places=2)
	description = models.TextField()
	buyableType = models.ManyToManyField(BuyableType)
	barcode = models.CharField(max_length=100, default='', blank=True)
	

	def hasDeposit(self):
		""" Returns True if the item has deposit. """
		return self.deposit > Decimal(0)
	
	def createPurchase(self, isDeposit=False):
		""" Creates a :class:`Purchase` containing this :class:`Buyable`. """
		p = Purchase()
		if isDeposit:
			p.price = self.deposit
		else:
			p.price = self.price
		p.dateTime = datetime.datetime.now()
		p.buyable = self
		
		return p
	
	def __unicode__(self):
		item = "%s (%.2f EUR" % (self.name, self.price)
		if self.hasDeposit():
			item += "/%.2f Pfand" % self.deposit
		item += ")"
		return item

class Order(models.Model):
	""" Represents an order by the user, consists of several :class:`Purchases <Purchase>`. """
	user = models.ForeignKey(User)
	price = models.DecimalField(max_digits=8, decimal_places=2)
	dateTime = models.DateTimeField()

	def create(self, user=None):
		models.Model.__init__(self)
		self.price = Decimal(0)
		self.dateTime = datetime.datetime.now()
		if user:
			self.user = user
	
	def addItems(self, items):
		for item in items:
			self.purchase.add(item)
			self.price += item.price
	
	def updatePrice(self, commit=False, updateBalance=False):
		self.price = Decimal(0)
		for item in self.purchase_set.all():
			self.price += item.price
		if commit or updateBalance:
			# TROLL MODE ON!
			profile = self.user.get_profile()
			profile.balance -= self.price
			profile.save()
	
	def __unicode__(self):
		return "Price %s, User %s" % (self.price, self.user)
	
	#def save(self, *args, **kwargs):
		#profile = self.user.get_profile()
		#if self.id == None:
			## new item, get it!
			#profile.balance -= self.price
			#profile.save()
		#else:
			## get old 
		#super(Order, self).save(*args, **kwargs)


class Purchase(models.Model):
	""" Represents a :class:`Buyable` in a :class:`Order`"""
	order = models.ForeignKey(Order)
	price = models.DecimalField(max_digits=8, decimal_places=2)
	isDeposit = models.BooleanField()
	buyable = models.ForeignKey(Buyable)

	@staticmethod
	def create(order, buyable, isDeposit=False):
		""" Create a Purchase from a buyable. Still needs to be saved. """
		p = Purchase()
		p.order = order
		p.isDeposit = isDeposit
		if p.isDeposit:
			p.price = buyable.deposit
		else:
			p.price = buyable.price
		p.dateTime = datetime.datetime.now()
		p.buyable = buyable
		
		return p

	def __unicode__(self):
		return "%s%s" % (self.buyable.name, (self.isDeposit and " (deposit)" or ""))

