from django.db import models
from django.contrib.auth.models import User
from utils.models import Personnel,Role,Institution,PersonnelInstitution,Structure,PersonnelStructure
import random
import datetime
# Create your models here.
# Product Models ----

# Types of Products of the App
class TypeProduct(models.Model):
	m_name = models.CharField(blank=True,null=True,max_length=128)
	m_fields = models.TextField(blank=True,null=True)
	m_structure = models.ForeignKey(Structure,blank=True,null=True,on_delete=models.CASCADE)
	m_institution = models.ForeignKey(Institution,blank=True,null=True,on_delete=models.CASCADE)

	def montant_products(self):
		rst = 0
		for pro in TransactionProduct.objects.filter(m_product__m_type__id = self.id):
			rst += pro.total()
		return rst

	def nb_ventes(self):
		return  TransactionProduct.objects.filter(m_product__m_type__id = self.id).count()

	def mini_name(self):
		return str(self.m_name[:4])

	def __str__(self):
		return self.m_name

	class Meta:
		verbose_name = "Type de Produit"
		verbose_name_plural = "Types de Produit"
	class Meta:
		ordering=('m_name',)

# Products of the App
class Product(models.Model):
	m_code = models.CharField(blank=True,null=True,max_length=32)
	m_name = models.CharField(blank=True,null=True,max_length=128)
	m_logo = models.FileField(blank=True,null=True)
	m_type = models.ForeignKey(TypeProduct,blank=True,null=True,on_delete=models.CASCADE)
	m_price = models.FloatField(blank=True,null=True)
	m_qte = models.PositiveIntegerField(blank=True,null=True)

	m_unite =  models.CharField(blank=True,null=True,max_length=32)

	is_promo = models.BooleanField(blank=True,null=True)
	promo_date = models.DateTimeField(blank=True,null=True)
	promo_duration = models.IntegerField(default=7,blank=True,null=True)
	m_description = models.TextField(blank=True,null=True)
	m_structure = models.ForeignKey(Structure,blank=True,null=True,on_delete=models.CASCADE)
	m_institution = models.ForeignKey(Institution,blank=True,null=True,on_delete=models.CASCADE)
	
	def __str__(self):
		return self.m_name

	def ravitaille_urgent(self):
		average_qte = 0
		dd = datetime.date.today()
		date_list = [dd - datetime.timedelta(days=x) for x in range(2)]
		for pro in TransactionProduct.objects.filter(m_product__id = self.id,m_transaction__m_date__date__in= date_list):
			average_qte += pro.m_qte
		if self.m_qte == None :
			return False
		if average_qte >= self.m_qte or self.m_qte == 0:
			return True

	def recommanded_qte(self):
		average_qte = 0
		dd = datetime.date.today()
		date_list = [dd - datetime.timedelta(days=x) for x in range(2)]
		for pro in TransactionProduct.objects.filter(m_product__id = self.id,m_transaction__m_date__date__in= date_list):
			average_qte += pro.m_qte
		return average_qte
	
	def to_promote(self):
		result = False
		if TransactionProduct.objects.filter(m_product__id = self.id).count() > 20:
			result = True
		return result

	def in_promotion(self):
		result = False
		if self.promo_date != None:
			dd = datetime.date.today()
			date_list = [self.promo_date.date() + datetime.timedelta(days=x) for x in range(self.promo_duration)]
			if dd in date_list:
				result = True
		return result

	def montant_products(self):
		rst = 0
		for pro in TransactionProduct.objects.filter(m_product__id = self.id):
			rst += pro.total()
		return rst

	def nb_ventes(self,period=None):
		return  TransactionProduct.objects.filter(m_product__id = self.id).count()

	class Meta:
		verbose_name = "Produit"
		verbose_name_plural = "Produits"
		ordering=('m_code',)

# Customer Models -----
class Customer(models.Model):
	m_code = models.CharField(blank=True,null=True,max_length=128)
	m_name = models.CharField(blank=True,null=True,max_length=128)
	m_date_saved = models.DateTimeField(auto_now_add=True,blank=True,null=True)
	m_picture = models.FileField(blank=True,null=True)
	m_tel = models.TextField(blank=True,null=True)
	m_gmail = models.TextField(blank=True,null=True)
	m_institution = models.ForeignKey(Institution,blank=True,null=True,on_delete=models.CASCADE)
	class Meta:
		verbose_name = "Client"
		verbose_name_plural = "Clients"
	def __str__(self):
		return self.m_name

# Types of Transaction Models ----
class TypeTransaction(models.Model):
	m_name = models.CharField(blank=True,null=True,max_length=128)
	class Meta:
		verbose_name = "Transaction"
		verbose_name_plural = "Types de Transaction"
	def __str__(self):
		return self.m_name


class Fournisseur(models.Model):
	m_code = models.CharField(blank=True,null=True,max_length=128)
	m_name = models.CharField(blank=True,null=True,max_length=128)
	m_localisation = models.TextField(blank=True,null=True)
	m_tel = models.TextField(blank=True,null=True)
	m_gmail = models.TextField(blank=True,null=True)
	m_institution = models.ForeignKey(Institution,blank=True,null=True,on_delete=models.CASCADE)
	class Meta:
		verbose_name = "Fournisseur"
		verbose_name_plural = "Fournisseurs"

	def __str__(self):
		return self.m_name

	def users(self):
		return FournisseurUser.objects.filter(m_fournisseur__id=self.id)

class FournisseurUser(models.Model):
	m_fournisseur = models.ForeignKey(Fournisseur,blank=True,null=True,on_delete=models.CASCADE)
	m_user = models.ForeignKey(User,blank=True,null=True,on_delete=models.CASCADE)
	m_tel = models.TextField(blank=True,null=True)
	def __str__(self):
		return str(self.m_user)

class ProductsFournisseur(models.Model):
	m_product = models.ForeignKey(Product,on_delete=models.CASCADE,blank=True,null=True)
	m_fournisseur = models.ForeignKey(Fournisseur,on_delete=models.CASCADE,blank=True,null=True)
	m_prix = models.IntegerField(blank=True,null=True)
	m_qte = models.IntegerField(blank=True,null=True)

# Transactions Models
class Transaction(models.Model):
	m_code = models.CharField(blank=True,null=True,max_length=32)
	m_date = models.DateTimeField(auto_now=True,blank=True,null=True)
	m_sens = models.IntegerField(blank=True,null=True)#0: Vente
	m_description = models.TextField(blank=True,null=True)
	
	m_customer =  models.ForeignKey(Customer,blank=True,null=True,on_delete=models.CASCADE)
	m_structure =  models.ForeignKey(Structure,blank=True,null=True,on_delete=models.CASCADE)
	m_institution = models.ForeignKey(Institution,blank=True,null=True,on_delete=models.CASCADE)

	m_staff = models.ForeignKey(User,blank=True,null=True,on_delete=models.CASCADE)
	def products(self):
		products = TransactionProduct.objects.filter(m_transaction = self.id)
		return products

	def montant(self):
		t_products = TransactionProduct.objects.filter(m_transaction = self.id)
		sum = 0
		for pro in t_products:
			sum += pro.total()
		return sum

	def client(self):
		if self.m_customer == None:
			return "Non identifié"
		else:
			return str(self.m_customer)

	def readable_sense(self):
		if self.m_sens == 0:
			return "Vente"
		elif self.m_sens == 0:
			return "Achat"

	def __str__(self):
		return str(self.m_date) + ' - '+ str(self.m_code)

	class Meta:
		verbose_name = "Transaction"
		verbose_name_plural = "Transactions"
		ordering=('-m_date',)

# Profuct manipulated over transactions
class TransactionProduct(models.Model):
	m_transaction = models.ForeignKey(Transaction,null=True,on_delete=models.CASCADE)
	m_product = models.ForeignKey(Product,null=True,on_delete=models.CASCADE)
	m_qte = models.IntegerField(blank=True,null=True)
	m_forced_value  = models.IntegerField(blank=True,null=True)
	def total(self):
		if self.m_forced_value == None:
			return self.m_qte * self.m_product.m_price
		else:
			return self.m_forced_value

	class Meta:
		verbose_name = "Produit par Transaction"
		verbose_name_plural = "Produit par Transactions"
		ordering=('-id',)
	def __str__(self):
		return str(self.m_transaction) + " - "+str(self.m_product) + " : "+str(self.m_qte)

class Ravitaillement(models.Model):
	m_ravitailleur = models.ForeignKey(FournisseurUser,null=True,on_delete=models.CASCADE)
	m_produit = models.ForeignKey(Product,null=True,on_delete=models.CASCADE)
	m_qte = models.IntegerField(blank=True,null=True)
	m_date_ravit = models.DateTimeField(auto_now=True,blank=True,null=True)