from django.db import models
from authentication.models import User
from customer.models import Customer
from django.utils import timezone
from django.conf import settings
import os
import logging
from django.core.exceptions import ValidationError
from supplier.models import Supplier,Supplier_Bill
from authentication.models import ActivityLog


class BaseModel(models.Model):
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='%(class)s_created', null=True, blank=True)
    updated_by = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='%(class)s_updated', null=True, blank=True)
    deleted_by = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='%(class)s_deleted', null=True, blank=True)

    created_at = models.DateTimeField(auto_now_add=True,null=True)
    updated_at = models.DateTimeField(auto_now=True,null=True)
    deleted_at = models.DateTimeField(null=True, blank=True)


    class Meta:
        abstract = True

class ProductCategory(BaseModel):
    category_name = models.CharField(max_length=255)
    allow_price_edit=models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
   
    soft_deleted = models.BooleanField(default=False)
    def soft_delete(self):
        # Soft delete the product category
        self.is_active = False
        self.deleted_at = timezone.now()
        self.save()

    def undelete(self):
        # Restore the product category
        self.is_active = True
        self.deleted_at = None
        self.save()

    def __str__(self):
        return self.category_name
        
    def get_status(self):
         return "Active" if self.is_active else "Inactive"



 
class Product(BaseModel):
    uid=models.TextField(null=True)
    sku = models.CharField(max_length=50,null=True)
    TYPE_CHOICES = (
        ('used', 'Used'),
        ('new', 'New'),
    )
    product_type = models.CharField(max_length=10, choices=TYPE_CHOICES)
    category = models.ForeignKey('ProductCategory', on_delete=models.CASCADE)
    product_name = models.CharField(max_length=255,null=True)
    product_description = models.TextField()  # Use a rich text field like CKEditor
    product_specification_contents = models.TextField()  # Use a rich text field like CKEditor
    product_image_main = models.ImageField(upload_to='product_images/main_images/')
    product_price = models.DecimalField(max_digits=10, decimal_places=2)
    specification_pdf = models.FileField(upload_to='specification_pdfs/')
    is_product=models.PositiveSmallIntegerField(default=0)
    is_active = models.BooleanField(default=True)
  
   
    def price(self):
        return "{:,.2f}".format(self.product_price)
   


   
    def soft_delete(self):
       
        self.is_active = False
        self.deleted_at = timezone.now()
        self.save()

    def undelete(self):
        
        self.is_active = True
        self.deleted_at = None
        self.save()

    def __str__(self):
        return self.product_name
        
    def get_status(self):
         return "Active" if self.is_active else "Inactive"

    
class OtherImage(BaseModel):
    product=models.ForeignKey(Product, on_delete=models.CASCADE,null=True, related_name='other_images')
    other_images = models.ImageField(upload_to='product_images/other_images/')
    def __str__(self):
       return str(self.product)




   
class SerialNumber(BaseModel):
    ORDERED = 0
    SHIPPED = 1
    WATERED = 2
    ARRIVED = 3
    BOOKED_FOR_INSTALL= 4
    INSTALLED=5

    TRACKING_STATUS_CHOICES = (
        (ORDERED, 'Ordered'),
        (SHIPPED, 'Shipped'),
        (WATERED, 'Watered'),
        (ARRIVED, 'Arrived'),
        (BOOKED_FOR_INSTALL, 'Booked For Install'),
        (INSTALLED, 'Installed'),
    )
   
    OPEN=0
    UNALLOCATED=1
    ALLOCATED=2

    STATUS_CHOICES = (
        (OPEN, 'Open'),
        (UNALLOCATED,'Unallocated'),
        (ALLOCATED, 'Allocated'),
    )
    serial_number = models.CharField(max_length=255,null=True,blank=True)
    product = models.ForeignKey(Product, on_delete=models.CASCADE,null=True)
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE,null=True)
    Arrival_ETA_date=models.DateField(auto_now=False, auto_now_add=False, null=True)
    arrived_date = models.DateField(auto_now=False, auto_now_add=False, null=True)
    invoice =  models.ForeignKey('quotation.Invoice', on_delete=models.CASCADE,null=True,blank=True)
    supplier =  models.ForeignKey(Supplier, on_delete=models.CASCADE, null=True, blank=True ,related_name='supplier')
    bill = models.ForeignKey('supplier.Supplier_Bill', on_delete=models.CASCADE,null=True,)
    is_active = models.BooleanField(default=True)
    status =models.PositiveSmallIntegerField(choices=STATUS_CHOICES,default=0,null=True)
    tracking_status =models.PositiveSmallIntegerField(choices=TRACKING_STATUS_CHOICES,default=0,null=True)
    bill_identifier = models.IntegerField(null=True)
    def __str__(self):
        return str(self.id)
    
    def soft_delete(self):

        self.is_active = False
        self.deleted_at = timezone.now()
        self.save()
        
  
    @property           
    def get_order_number(self):
        from quotation.models import Order_Item
        order_number= Order_Item.objects.filter(serial_number__id=self.id).first()
        if order_number:
            return order_number.order.id
        else:
            return None
    
    @property           
    def get_tracking_status(self):
        if self.tracking_status == 0:
            return "Ordered"
        if self.tracking_status == 1:
            return "Shipped"
        if self.tracking_status == 2:
            return "Watered"
        if self.tracking_status == 3:
            return "Arrived"
        if self.tracking_status == 4:
            return "Booked For Install"
        if self.tracking_status == 5:
            return "Installed"
    
    @property           
    def get_self_status(self):
        if self.status == 0:
            return "Open"
        if self.status == 1:
            return "Unallocated"
        if self.status == 2:
            return "Allocated"
       
        
    
   
    @property           
    def get_order_item_id(self):
        from quotation.models import Order_Item
        order_number= Order_Item.objects.filter(serial_number__id=self.id).first()
        if order_number:
            return order_number.id
        else:
            return None
    
    
    
    @property           
    def get_serial_history(self):
        # Assuming an invoice can have multiple invoice items
        # and we're getting the supplier from the first invoice item
        order_history= ActivityLog.objects.filter(model_name='SerialNumber' , instance_id = self.id ).order_by('id')
        
        if order_history:
            return order_history
        else:
            return None   

    def get_status(self):
         return "Active" if self.is_active else "Inactive"
    

   