from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class Institution(models.Model):
	m_logo = models.FileField(blank=True,null=True)
	m_name = models.CharField(max_length=128,blank=True,null=True)
	m_description = models.TextField(blank=True,null=True)
	m_website = models.CharField(max_length=128,blank=True,null=True)
	def __str__(self):
		return str(self.m_name)

class Structure(models.Model):
	m_logo = models.FileField(blank=True,null=True)
	m_name = models.CharField(max_length=128,blank=True,null=True)
	m_description = models.TextField(blank=True,null=True)
	m_institution = models.ForeignKey(Institution,on_delete=models.CASCADE,null=True,blank=True)
	def __str__(self):
		return str(self.m_name)

class Role(models.Model):
	m_name = models.CharField(max_length=128,blank=True,null=True)
	m_description = models.TextField(blank=True,null=True)
	m_institution = models.ForeignKey(Institution,on_delete=models.CASCADE,null=True,blank=True)
	m_permissions = models.IntegerField(blank=True,null=True)
	def __str__(self):
		return str(self.m_name)

class Personnel(models.Model):
	m_user = models.OneToOneField(User,on_delete=models.CASCADE,blank=True,null=True)
	m_permissions = models.IntegerField(blank=True,null=True)
	m_tel = models.CharField(max_length=24,blank=True,null=True) 
	m_actual_institution = models.ForeignKey(Institution,on_delete=models.CASCADE,null=True,blank=True)
	def __str__(self):
		return str(self.m_user)

class PersonnelInstitution(models.Model):
	m_personnel = models.ForeignKey(Personnel,on_delete=models.CASCADE,null=True,blank=True)
	m_role = models.ForeignKey(Role,on_delete=models.CASCADE,null=True,blank=True)

class PersonnelStructure(models.Model):
	m_personnel = models.ForeignKey(Personnel,on_delete=models.CASCADE,null=True,blank=True)
	m_structure = models.ForeignKey(Structure,on_delete=models.CASCADE,null=True,blank=True)
	m_sub_role = models.CharField(max_length=128,blank=True,null=True) 
	
class Facture(models.Model):
	m_html_code = models.TextField(blank=True,null=True)
	m_institution = models.ForeignKey(Institution,on_delete=models.CASCADE,null=True,blank=True)
	def __str__(self):
		return "Facture : "+str(self.m_institution)
	def parse(self,transaction):
		products = transaction.products()
		products_infos = ""
		for prd in products:
			price = prd.m_product.m_price
			products_infos += "<tr> <td>"+ str(prd.m_qte) +" </td>" + "<td>"+ str(prd.m_product) +" </td>  <td>"+str(price)+"</td> <td>"+str(prd.total())+"</td> <tr>"
	
		html_code = self.m_html_code
		html_code = html_code.replace("$m_code ",transaction.m_code).replace("$m_date",str(transaction.m_date) )
		html_code = html_code.replace("$m_nom","___________________________________").replace("$m_tel","_________")

		html_code = html_code.replace("<tr class='facture_line'></tr>",products_infos)
		html_code = html_code.replace("$f_total$",  str(transaction.montant()) )
		return html_code
