from django.db import models

# Create your models here.
from django.db.models.signals import pre_save, post_save
from carts.models import Cart
from khaja.utils import unique_order_id_generator
from users.models import User
from addresses.models import Address

ORDER_STATUS_CHOICES = (
    ('Recieved','Recieved'),
    ('Processing', 'Processing'),
    ('Prepared', 'Prepared'),
    ('Shipped', 'Shipped'),
    ('Paid', 'Paid'),
)


class Order(models.Model):
    order_id = models.CharField(max_length=120, blank=True)
    user = models.ForeignKey(User)
    cart = models.OneToOneField(Cart,on_delete=models.CASCADE, primary_key=True)
    status = models.CharField(max_length=120, default="Recieved", choices=ORDER_STATUS_CHOICES)
    total = models.DecimalField(default=0.0, max_digits=100, decimal_places=2)
    address = models.ForeignKey(Address)
    created_at = models.DateField(auto_now_add=True)
    updated_at = models.DateField(auto_now=True)

    def __str__(self):
        return self.order_id

    class Meta:
        db_table = "orders"

    def update_total(self):
        new_total = self.cart.total
        self.total = new_total
        self.save()
        return new_total


def pre_save_create_order_id(sender, instance, *args, **kwargs):
    if not instance.order_id:
        instance.order_id = unique_order_id_generator(instance)


pre_save.connect(pre_save_create_order_id, sender=Order)


def post_save_cart_total(sender, instance, created, *args, **kwargs):
    if not created:
        cart_obj = instance
        cart_obj.is_true = False
        cart_id = cart_obj.id
        qs = Order.objects.filter(cart__id=cart_id)
        if qs.count() == 1:
            order_obj = qs.first()
            order_obj.update_total()


post_save.connect(post_save_cart_total, sender=Cart)


def post_save_order_total(sender, instance, created, *args, **kwargs):
    if created:
        instance.update_total()


post_save.connect(post_save_order_total, sender=Order)
