# 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.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from decimal import Decimal

class UserProfile(models.Model):
	""" Contains data for a user, especially the account balance. """
	user = models.ForeignKey(User, unique=True)
	balance = models.DecimalField(max_digits=9, decimal_places=2, default=Decimal(0))
	balance.has_negative_filter = True

	def balance_negative(self):
		return (self.balance < 0)
	
	def __unicode__(self):
		return "%s (Kontostand: %s)" % (self.user ,self.balance)
	
def createUserProfile(sender, instance, created, **kwargs):
	""" Hook to create a new :class:`UserProfile` when the user is created. """
	if created:
		profile = UserProfile()
		profile.user = instance
		profile.save()

post_save.connect(createUserProfile, sender=User)

class Plugin(models.Model):
	""" This Model contains a plugin and its configuration.
	
	A Plugin consists of its own information (name, author, version
	and description, which are displayed on the plugin
	selection page), a configuration of what a plugin is allowed to do
	and what not and an own user for authentication against the
	API.
	
	:attr:`uniqueAuthblob` is used if the :class:`Plugin` has to uniquely
	identify a user by his/her :attr:`authblob <PluginPermission.authblob>`.
	The other attributes are used for plugin/user read/write access to the
	authblob.
	"""
	user = models.ForeignKey(User, unique=True)
	
	# plugin info
	name = models.CharField(max_length=40)
	author = models.CharField(max_length=40)
	version = models.CharField(max_length=40)
	descr = models.TextField(default='')
	
	# plugin config
	uniqueAuthblob = models.BooleanField(default=False)
	userCanWriteAuthblob = models.BooleanField(default=True)
	maxLinesPerAuthblob = models.IntegerField(default=0)
	
	# automatically set when write is allowed
	userCanReadAuthblob = models.BooleanField(default=True)
	pluginCanWriteAuthblob = models.BooleanField(default=False)
	pluginCanReadAuthblob = models.BooleanField(default=False)
	
	def __unicode__(self):
		return self.name

class PluginPermission(models.Model):
	""" States that a user allows access to his/her account to a :class:`Plugin`.
	
		The :attr:`authblob` can be used by the Plugin to store
		authentication data, e.g. a barcode or hashed password.
	"""
	user = models.ForeignKey(User)
	plugin = models.ForeignKey('Plugin')
	
	#: authblob which holds arbitrary authentication data.
	authblob = models.TextField(default='')
	
	def __unicode__(self):
		return "%s allows %s" % (self.user, self.plugin)
