# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User, Permission
from django.db.models.signals import post_save, pre_delete

from product.models import Product
from fabric.models import Fabric


## User Profile Class
#
class UserProfile(models.Model):
	user = models.OneToOneField(User)
	name = models.CharField(max_length=128)
	valid = models.BooleanField(default=True) #visible
	userFabricCount = models.IntegerField(default=0) #how many fabric can user upload
	USERTYPE_CHOICES = (
		(1, 'user'),
		(2, 'uploader'),
		(3, 'admin'),
	)
	userType = models.IntegerField(default=1, choices=USERTYPE_CHOICES)
	client_group = models.ForeignKey('ClientGroup', default=None, null=True)
	
	def __unicode__(self):
		return self.name
	
# When you add User, automatically post save UserProfile
# And, if you wanna approach it, you can call user.get_profile()	
def create_user_profile(sender, instance, created, **kwargs):
	if created:
		UserProfile.objects.create(user=instance)
	elif instance.is_staff:
		instance.userprofile.userType = 3
		instance.userprofile.save()

post_save.connect(create_user_profile, sender=User)

class ClientGroup(models.Model):
	name = models.CharField(max_length=128)
	accessible_fabric = models.ManyToManyField(Fabric, through='Access_to_fabric', related_name='allowed_groups')
	accessible_product = models.ManyToManyField(Product, through='Access_to_product', related_name='allowed_groups')
	
	def __unicode__(self):
		return self.name

class Access_to_fabric(models.Model):
    client_group = models.ForeignKey(ClientGroup)
    fabric = models.ForeignKey(Fabric)
    
    class Meta:
        unique_together = (('client_group', 'fabric'), )

class Access_to_product(models.Model):
    client_group = models.ForeignKey(ClientGroup)
    product = models.ForeignKey(Product)
    
    class Meta:
        unique_together = (('client_group', 'product'), )