from django.db import models
# Used to generate URLs by reversing the URL patterns
from django.urls import reverse
from django.db.models import Sum

# Create your models here.


class Houtsoort(models.Model):
    Hout_ID = models.AutoField(primary_key=True)
    Houtsoort_naam = models.CharField(max_length=255, help_text='Houtsoort')

    def get_absolute_url(self):
        """Returns the url to access a particular instance of the model."""
        return reverse('model-detail-view', args=[str(self.Hout_ID)])

    def __str__(self):
        """String for representing the Model object."""
        return self.Houtsoort_naam

    class Meta:
        db_table = "Houtsoort"
        verbose_name_plural = "Houtsoorten"


class Formaat(models.Model):
    Format_ID = models.AutoField(primary_key=True)
    Formaat = models.CharField(max_length=255, help_text='Formaat (vb 2x4)')
    Lengte = models.FloatField()

    def get_absolute_url(self):
        """Returns the url to access a particular instance of the model."""
        return reverse('model-detail-view', args=[str(self.Format_ID)])

    def __str__(self):
        """String for representing the Model object."""
        return self.Formaat + " " + str(self.Lengte) + "m"

    class Meta:
        db_table = "Formaat"
        verbose_name_plural = "Formaten"


class Houtmarkt(models.Model):
    Houtmarkt_ID = models.AutoField(primary_key=True)
    Houtmarkt_naam = models.CharField(
        max_length=255, help_text='Houtmarkt naam')
    Houtmarkt_tel = models.IntegerField()
    Houtmarkt_addr = models.CharField(max_length=255)
    TYPES = (
        ("RE", "Reseller"),
        ("SE", "Seller")
    )
    Houtmarkt_type = models.CharField(
        max_length=2,
        choices=TYPES
    )

    def get_absolute_url(self):
        """Returns the url to access a particular instance of the model."""
        return reverse('model-detail-view', args=[str(self.Houtmarkt_ID)])

    def __str__(self):
        """String for representing the Model object."""
        return self.Houtmarkt_naam

    class Meta:
        db_table = "Houtmarkt"
        verbose_name_plural = "Houtmarkten"


class Voorraad(models.Model):
    Voorraad_ID = models.AutoField(primary_key=True)
    Houtmarkt_ID = models.ForeignKey("Houtmarkt", on_delete=models.PROTECT)
    Hout_ID = models.ForeignKey("Houtsoort", on_delete=models.PROTECT)
    Format_ID = models.ForeignKey("Formaat", on_delete=models.PROTECT)
    Prijs = models.FloatField()
    Voorraad_Amount = models.IntegerField()

    def get_absolute_url(self):
        """Returns the url to access a particular instance of the model."""
        return reverse('model-detail-view', args=[str(self.Voorraad_ID)])

    def __str__(self):
        """String for representing the Model object."""
        return str(self.Format_ID) + " " + self.Hout_ID.Houtsoort_naam

    class Meta:
        db_table = "Voorraad"
        verbose_name_plural = "Voorraad"


class Klant(models.Model):
    Klant_ID = models.AutoField(primary_key=True)
    Klant_naam = models.CharField(max_length=255, help_text='Klant naam')
    Klant_tel = models.CharField(
        max_length=255, help_text='Klant telefoon nummer')
    Klant_Addr = models.CharField(max_length=255, help_text='Klant Adres')
    Is_Houtmarkt = models.BooleanField()

    def get_absolute_url(self):
        """Returns the url to access a particular instance of the model."""
        return reverse('model-detail-view', args=[str(self.Klant_ID)])

    def __str__(self):
        """String for representing the Model object."""
        return self.Klant_naam

    class Meta:
        db_table = "Klant"
        verbose_name_plural = "Klanten"


class Order(models.Model):
    Order_ID = models.AutoField(primary_key=True)
    Voorraad_ID = models.ForeignKey("Voorraad", on_delete=models.PROTECT)
    # Factuur_ID = models.ForeignKey("Factuur", on_delete=models.PROTECT)
    Amount = models.IntegerField()

    Prijs = models.FloatField(null=True, blank=True)

    def get_absolute_url(self):
        """Returns the url to access a particular instance of the model."""
        return reverse('model-detail-view', args=[str(self.Order_ID)])

    def __str__(self):
        """String for representing the Model object."""
        return "{} {}".format(self.Amount, self.Voorraad_ID)

    class Meta:
        db_table = "Order"
        verbose_name_plural = "Orders"

    def save(self, *args, **kwargs):
        self.Prijs = round(self.Voorraad_ID.Prijs * self.Amount, 2)
        
        new_amount = self.Voorraad_ID.Voorraad_Amount - self.Amount
        if new_amount < 0:
            raise ValueError("Er zijn maar {} in voorraad".format(
                self.Voorraad_ID.Voorraad_Amount))
        self.Voorraad_ID.Voorraad_Amount -= self.Amount
        self.Voorraad_ID.save()
        return super(Order, self).save(*args, **kwargs)


class Factuur(models.Model):
    Factuur_ID = models.AutoField(primary_key=True)
    Klant_ID = models.ForeignKey("Klant", on_delete=models.PROTECT)
    Orders = models.ManyToManyField("Order", blank=True)
    Korting_percent = models.FloatField()
    Subtotal = models.FloatField(null=True, blank=True)
    Total = models.FloatField(null=True, blank=True)
    Date = models.DateTimeField(auto_now_add=True)
    def get_absolute_url(self):
        """Returns the url to access a particular instance of the model."""
        return reverse('factuur-detail', args=[str(self.Factuur_ID)])

    def __str__(self):
        """String for representing the Model object."""
        return str(self.Factuur_ID)

    @property
    def subtotal(self):
        if not self.Subtotal:
            self.Subtotal = round(self.Orders.all().aggregate(Sum('Prijs'))['Prijs__sum'], 2)
            self.save()
        return self.Subtotal
 
    @property
    def total(self):
        if self.pk:
            if not self.Total:
                self.Total = (100 - self.Korting_percent) * self.subtotal / 100
                self.Total = round(1.08 * self.Total , 2)
                self.save()
            return self.Total
        else:
            return 0
    class Meta:
        db_table = "Factuur"
        verbose_name_plural = "Facturen"
