from django.db import models
import os

from snow_flake_api.settings import MEDIA_ROOT


def sku_picture_path(instance, filename):
    return os.path.join(
        "items/item_"
        + str(instance.skuId.itemId.id)
        + "/sku_"
        + str(instance.skuId.id)
        + "/images/",
        instance.skuId.name + "."+instance.extension,
    )


def sku_video_path(instance, filename):
    ext = filename.split(".")
    return os.path.join(
        "items/item_"
        + str(instance.skuId.itemId.id)
        + "/sku_"
        + str(instance.skuId.id)
        + "/images/",
        ext[0] + "." + ext[1],
    )

def brand_picture_path(instance, filename):
    ext = filename.split(".")
    return os.path.join("brands/brand_" + str(instance.id), ext[0] + "." + ext[1])


def appContent_picture_path(instance, filename):
    ext = filename.split(".")
    return os.path.join(
        "appcontents/appcontent_" + str(instance.id), ext[0] + "." + ext[1]
    )


def supplier_file_document_path(instance, filename):
    ext = filename.split(".")
    return os.path.join(
        "suppliers/supplier_" + str(instance.supplierId.id), ext[0] + "." + ext[1]
    )

# Start of Data View

class DashboardData:
    def __init__(
        self,
        countItems,
        sumPaymentTotal,
        sumPaymentPaid,
        sumPaymentChange,
        countTransactionIn,
        sumTransactionInTotal,
        sumTransactionInPaid,
        countTransactionOut,
        sumTransactionOutTotal,
        sumTransactionOutPaid,
        currentBalanceTotal,
        currentBalancePaid,
        currentSumTaxes,
    ):
        self.countItems = countItems
        self.sumPaymentTotal = sumPaymentTotal
        self.sumPaymentPaid = sumPaymentPaid
        self.sumPaymentChange = sumPaymentChange
        self.countTransactionIn = countTransactionIn
        self.sumTransactionInTotal = sumTransactionInTotal
        self.sumTransactionInPaid = sumTransactionInPaid
        self.countTransactionOut = countTransactionOut
        self.sumTransactionOutTotal = sumTransactionOutTotal
        self.sumTransactionOutPaid = sumTransactionOutPaid
        self.currentBalanceTotal = currentBalanceTotal
        self.currentBalancePaid = currentBalancePaid
        self.currentSumTaxes = currentSumTaxes

# End of Data View

# Start Basic Data
class Settings(models.Model):
    isMaintenanceClient = models.BooleanField(default=False)
    isMaintenanceSupplier = models.BooleanField(default=False)
    isEnableFreeSubscriptionForSupplier = models.BooleanField(default=False)
    itemSKULimit = models.IntegerField(default=10)
    itemSKUOptionLimit = models.IntegerField(default=10)
    itemFeatureBulletLimit = models.IntegerField(default=10)
    maxCartQuantity = models.IntegerField(default=10)
    isEnableStoreBankCards = models.BooleanField(default=False)
    isShowBrands = models.BooleanField(default=False)
    isInitialSettingsDone = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class Language(models.Model):
    name = models.TextField(default="")
    countryCode = models.CharField(default="", max_length=10)
    languageCode = models.CharField(default="", max_length=10)
    isEnabled = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

    def __str__(self):
        return str(self.name)


class SocialLink(models.Model):
    name = models.CharField(default="", max_length=100)
    url = models.TextField(default="")
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

    def __str__(self):
        return str(self.name)

class SocialLinkToken(models.Model):
    token = models.TextField()
    longToken = models.TextField()
    timeInSeconds = models.IntegerField(default=0)
    socialLinkId = models.ForeignKey(
        SocialLink,
        on_delete=models.CASCADE,
        related_name="sociallink_sociallinktoken",
    )


class RegisterType(models.Model):
    keyName = models.CharField(default="", max_length=100)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class RegisterTypeLanguage(models.Model):
    name = models.TextField(default="")
    registerTypeId = models.ForeignKey(
        RegisterType,
        on_delete=models.CASCADE,
        related_name="registerType_registerTypelanguage",
    )
    languageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_registerTypelanguage"
    )


class OrderFrom(models.Model):
    keyName = models.CharField(default="", max_length=100)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class OrderFromLanguage(models.Model):
    name = models.CharField(default="", max_length=100)
    orderFromId = models.ForeignKey(
        OrderFrom, on_delete=models.CASCADE, related_name="orderfrom_orderfromlanguage"
    )
    languageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_orderfromlanguage"
    )


class ReturnStatus(models.Model):
    keyName = models.CharField(default="", max_length=100)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class ReturnStatusLanguage(models.Model):
    name = models.TextField(default="")
    returnStatusId = models.ForeignKey(
        ReturnStatus,
        on_delete=models.CASCADE,
        related_name="returnstatus_returnstatuslanguage",
    )
    languageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_returnstatuslanguage"
    )


class TrackStatus(models.Model):
    keyName = models.CharField(default="", max_length=100)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class TrackStatusLanguage(models.Model):
    name = models.TextField(default="")
    trackStatusId = models.ForeignKey(
        TrackStatus,
        on_delete=models.CASCADE,
        related_name="trackstatus_trackstatuslanguage",
    )
    languageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_tracktatuslanguage"
    )

class SKUCost(models.Model):
    serviceCost = models.FloatField(default=0)
    handlingCost = models.FloatField(default=0)
    packingCost = models.FloatField(default=0)
    taxCost = models.FloatField(default=0)
    cancelCost = models.FloatField(default=0)
    returnCost = models.FloatField(default=0)
    transactionFixedCost = models.FloatField(default=0)
    transactionFeeCost = models.FloatField(default=0)
    isEnabled = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

    def __str__(self):
        return str(self.id)

class PaymentMethod(models.Model):
    keyName = models.CharField(default="", max_length=100)
    isEnabled = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class PaymentMethodLanguage(models.Model):
    name = models.TextField(default="")
    paymentMethodId = models.ForeignKey(
        PaymentMethod,
        on_delete=models.CASCADE,
        related_name="paymentmethod_paymentmethodlanguage",
    )
    languageId = models.ForeignKey(
        Language,
        on_delete=models.CASCADE,
        related_name="language_paymentmethodlanguage",
    )

class TransactionType(models.Model):
    keyName = models.CharField(default="", max_length=100)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class TransactionTypeLanguage(models.Model):
    name = models.TextField(default="")
    transactionTypeId = models.ForeignKey(
        TransactionType,
        on_delete=models.CASCADE,
        related_name="transactiontype_transactiontypelanguage",
    )
    languageId = models.ForeignKey(
        Language,
        on_delete=models.CASCADE,
        related_name="language_transactiontypelanguage",
    )

class AppContent(models.Model):
    keyName = models.TextField(default="")
    isImage = models.BooleanField(default=False)
    image = models.ImageField(
        upload_to=appContent_picture_path,
        null=True,
        blank=True,
        default="/default/slider_holder.jpg",
    )
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

    def save(self, *args, **kwargs):
        if self.pk is None:
            saved_image = self.image
            self.image = None
            super(AppContent, self).save(*args, **kwargs)
            self.image = saved_image
            if "force_insert" in kwargs:
                kwargs.pop("force_insert")

        super(AppContent, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        if self.image and hasattr(self.image,'url'):
            if self.image.url != "/media/default/slider_holder.jpg":
                self.image.delete()
        super().delete()

class AppContentLanguage(models.Model):
    description = models.TextField(default="")
    appContentId = models.ForeignKey(
        AppContent,
        on_delete=models.CASCADE,
        related_name="appcontent_appcontentlanguage",
    )
    languageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_appcontentlanguage"
    )

class EligibleType(models.Model):
    keyName = models.CharField(default="", max_length=100)
    keyOption = models.CharField(default="", max_length=100)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class EligibleTypeLanguage(models.Model):
    name = models.TextField(default="")
    eligibleTypeId = models.ForeignKey(
        EligibleType,
        on_delete=models.CASCADE,
        related_name="eligibletype_eligibletypelanguage",
    )
    languageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_eligibletypelanguage"
    )

# Remove
class SubscriptionStatus(models.Model):
    keyName = models.CharField(default="", max_length=100)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class SubscriptionStatusLanguage(models.Model):
    name = models.TextField(default="")
    subscriptionStatusId = models.ForeignKey(
        SubscriptionStatus,
        on_delete=models.CASCADE,
        related_name="subscriptionstatus_subscriptionstatuslanguage",
    )
    languageId = models.ForeignKey(
        Language,
        on_delete=models.CASCADE,
        related_name="language_subscriptionstatuslanguage",
    )

# Remove
class SubscriptionOption(models.Model):
    keyName = models.CharField(default="", max_length=100)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class SubscriptionOptionLanguage(models.Model):
    name = models.TextField(default="")
    subscriptionOptionId = models.ForeignKey(
        SubscriptionOption,
        on_delete=models.CASCADE,
        related_name="subscriptionoption_subscriptionstatuslanguage",
    )
    languageId = models.ForeignKey(
        Language,
        on_delete=models.CASCADE,
        related_name="language_subscriptionoptionlanguage",
    )

# Remove
class SubscriptionType(models.Model):
    costPerMonth = models.FloatField(default=False)
    price = models.FloatField(default=0)
    discount = models.FloatField(default=0)
    serviceCost = models.FloatField(default=0)
    durationInMonth = models.IntegerField(default=0)
    isEnabled = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    subscriptionOptionId = models.ForeignKey(
        SubscriptionOption,
        on_delete=models.CASCADE,
        related_name="subscriptionoption_subscriptiontype",
    )

class SubscriptionTypeLanguage(models.Model):
    name = models.TextField(default="")
    subscriptionTypeId = models.ForeignKey(
        SubscriptionType,
        on_delete=models.CASCADE,
        related_name="subscriptiontype_subscriptiontypelanguage",
    )
    languageId = models.ForeignKey(
        Language,
        on_delete=models.CASCADE,
        related_name="language_subscriptiontypelanguage",
    )


class ShippingMethod(models.Model):
    keyName = models.TextField(default="")
    isEnabled = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

    def __str__(self):
        return str(self.id)

class ShippingMethodLanguage(models.Model):
    name = models.TextField(default="")
    shippingMethodId = models.ForeignKey(
        ShippingMethod, on_delete=models.CASCADE, related_name="shippingmethod_shippingmethodlanguage"
    )
    languageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_shippingmethodlanguage"
    )
# End of Basic Data


# Start of Departments
class Department(models.Model):
    keyName = models.TextField(default="")
    isVisible = models.BooleanField(default=False)
    totalViews = models.IntegerField(default=0)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    isMainDepartment = models.BooleanField(default=False)
    departmentId = models.ForeignKey(
        "self",
        on_delete=models.CASCADE,
        related_name="department_subdepartment",
        blank=True,
        null=True,
    )

class DepartmentLanguage(models.Model):
    name = models.TextField(default="")
    departmentId = models.ForeignKey(
        Department,
        on_delete=models.CASCADE,
        related_name="department_departmentlanguage",
    )
    languageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_departmentlanguage"
    )


class Brand(models.Model):
    keyName = models.TextField(default="")
    isVisible = models.BooleanField(default=False)
    image = models.ImageField(
        upload_to=brand_picture_path,
        null=True,
        blank=True,
        default="/default/holder.jpg",
    )
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

    def save(self, *args, **kwargs):
        if self.pk is None:
            saved_image = self.image
            self.image = None
            super(Brand, self).save(*args, **kwargs)
            self.image = saved_image
            if "force_insert" in kwargs:
                kwargs.pop("force_insert")

        super(Brand, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        if self.image and hasattr(self.image,'url'):
            if self.image.url != "/media/default/holder.jpg":
                self.image.delete()
        super().delete()

class BrandLanguage(models.Model):
    name = models.TextField(default="")
    brandId = models.ForeignKey(
        Brand, on_delete=models.CASCADE, related_name="brand_brandlanguage"
    )
    languageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_brandlanguage"
    )

# End of Departments


# Start of Location
class Country(models.Model):
    isActive = models.BooleanField(default=False)
    isMainBranch = models.BooleanField(default=False)
    dialCode = models.TextField(default='')
    currency = models.TextField(default='')
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class CountryLanguage(models.Model):
    name = models.TextField(default="")
    countryId = models.ForeignKey(
        Country, on_delete=models.CASCADE, related_name="country_countrylanguage"
    )
    languageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_countrylanguage"
    )


class State(models.Model):
    isActive = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    countryId = models.ForeignKey(
        Country, on_delete=models.CASCADE, related_name="country_state"
    )

class StateLanguage(models.Model):
    name = models.TextField(default="")
    stateId = models.ForeignKey(
        State,
        on_delete=models.CASCADE,
        related_name="state_statelanguage",
    )
    languageId = models.ForeignKey(
        Language,
        on_delete=models.CASCADE,
        related_name="language_statelanguage",
    )


class City(models.Model):
    isActive = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    stateId = models.ForeignKey(
        State, on_delete=models.CASCADE, related_name="state_city",
    )

class CityLanguage(models.Model):
    name = models.TextField(default="")
    cityId = models.ForeignKey(
        City,
        on_delete=models.CASCADE,
        related_name="city_citylanguage",
    )
    languageId = models.ForeignKey(
        Language,
        on_delete=models.CASCADE,
        related_name="language_citylanguage",
    )

# End of Location

class Client(models.Model):
    firstName = models.CharField(max_length=500)
    lastName = models.CharField(max_length=500)
    email = models.TextField(null=True, blank=True, default="")
    phone = models.TextField(default="")
    password = models.CharField(max_length=50, null=True, blank=True)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    registerTypeId = models.ForeignKey(
        RegisterType,
        on_delete=models.CASCADE,
        related_name="registertype_client",
        null=True,
        blank=True,
    )
    selectedLanguageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_client"
    )

    def __str__(self):
        return str(self.firstName)

class ClientAddressBook(models.Model):
    #phone = models.TextField(default="")
    address1 = models.TextField(default="")
    address2 = models.TextField(default="")
    zipCode = models.TextField(default="")
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    countryId = models.ForeignKey(
        Country, on_delete=models.CASCADE, related_name="country_clientaddressbook"
    )
    stateId = models.ForeignKey(
        State,
        on_delete=models.CASCADE,
        related_name="state_clientaddressbook",
        null=True,
        blank=True,
    )
    cityId = models.ForeignKey(
        City,
        on_delete=models.CASCADE,
        related_name="city_clientaddressbook",
        null=True,
        blank=True,
    )
    clientId = models.ForeignKey(
        Client, on_delete=models.CASCADE, related_name="client_clientaddressbook"
    )

    def __str__(self):
        return str(self.id)
    
class ClientCreditCard(models.Model):
    holder = models.TextField(default="")
    number = models.CharField(max_length=20)
    expireYear = models.IntegerField(default=0)
    expireMonth = models.IntegerField(default=0)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    clientId = models.ForeignKey(
        Client, on_delete=models.CASCADE, related_name="client_clientcreditcard"
    )

    def __str__(self):
        return str(self.id)


class Wallet(models.Model):
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    clientId = models.OneToOneField(
        Client, on_delete=models.CASCADE, primary_key=True, related_name="client_wallet"
    )

    def __str__(self):
        return str(self.clientId)

class Transaction(models.Model):
    amount = models.FloatField(default=0)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    transactionTypeId = models.ForeignKey(
        TransactionType,
        on_delete=models.CASCADE,
        related_name="transactiontype_transaction",
    )
    walletId = models.ForeignKey(
        Wallet, on_delete=models.CASCADE, related_name="wallet_transaction"
    )

    def __str__(self):
        return str(self.id)


class Supplier(models.Model):
    name = models.TextField(default="")
    email = models.TextField(default="")
    password = models.CharField(max_length=50, null=True, blank=True)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    isVerified = models.BooleanField(default=False)
    isFreeSubscriptionUsed = models.BooleanField(default=False)
    selectedLanguageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_supplier"
    )

    def __str__(self):
        return str(self.name)

class SupplierPhone(models.Model):
    phone = models.CharField(max_length=20)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    supplierId = models.ForeignKey(
        Supplier, on_delete=models.CASCADE, related_name="supplierphone_supplier"
    )

    def __str__(self):
        return str(self.id)

class SupplierCreditCard(models.Model):
    holder = models.CharField(max_length=250)
    number = models.CharField(max_length=20)
    expireYear = models.IntegerField()
    expireMonth = models.IntegerField()
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    supplierId = models.ForeignKey(
        Supplier, on_delete=models.CASCADE, related_name="supplier_creditcard"
    )

    def __str__(self):
        return str(self.id)

class SupplierDocument(models.Model):
    fileName = models.TextField(default="")
    contentType = models.TextField(default="")
    fileDocument = models.FileField(
        upload_to=supplier_file_document_path, null=True, blank=True
    )
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    supplierId = models.ForeignKey(
        Supplier, on_delete=models.CASCADE, related_name="supplierdocument_supplier"
    )

    def save(self, *args, **kwargs):
        if self.pk is None:
            saved_fileDocument = self.fileDocument
            self.fileDocument = None
            super(SupplierDocument, self).save(*args, **kwargs)
            self.fileDocument = saved_fileDocument
            if "force_insert" in kwargs:
                kwargs.pop("force_insert")

        super(SupplierDocument, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        supplierId = self.supplierId.id
        self.fileDocument.delete()
        super().delete()
        childPath = MEDIA_ROOT + "/suppliers/supplier_" + str(supplierId)
        if os.path.exists(childPath):
            dir = os.listdir(childPath)
            if len(dir) == 0:
                os.rmdir(childPath)


class Subscription(models.Model):
    price = models.FloatField(default=0)
    discount = models.FloatField(default=0)
    serviceCost = models.FloatField(default=0)
    startDate = models.DateTimeField()
    endDate = models.DateTimeField()
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    supplierId = models.ForeignKey(
        Supplier, on_delete=models.CASCADE, related_name="supplier_subscription"
    )
    subscriptionTypeId = models.ForeignKey(
        SubscriptionType,
        on_delete=models.CASCADE,
        related_name="subscriptiontype_subscription",
    )
    subscriptionStatusId = models.ForeignKey(
        SubscriptionStatus,
        on_delete=models.CASCADE,
        related_name="subscriptionstatus_subscription",
    )


class DeliveryMan(models.Model):
    name = models.TextField(default="")
    email = models.TextField(default="")
    password = models.CharField(max_length=50, null=True, blank=True)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    selectedLanguageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_delivery"
    )

    def __str__(self):
        return str(self.name)

class DeliveryManPhone(models.Model):
    phone = models.CharField(max_length=20)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    deliveryManId = models.ForeignKey(
        DeliveryMan, on_delete=models.CASCADE, related_name="deliveryman_phone"
    )

    def __str__(self):
        return str(self.id)

class ShippingCost(models.Model):
    price = models.FloatField(default=0)
    additionalPrice = models.FloatField(default=0) 
    isEnabled = models.BooleanField(default=False)
    workingDays = models.IntegerField(default=0)
    DeliveryDays = models.IntegerField(default=0)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    countryId = models.ForeignKey(
        Country, on_delete=models.CASCADE, related_name="country_shippingcost"
    )
    shippingMethodId = models.ForeignKey(
        ShippingMethod,
        on_delete=models.CASCADE,
        related_name="shippingmethod_shippingcost",
    )
    supplierId = models.ForeignKey(
        Supplier,
        on_delete=models.CASCADE,
        related_name="supplier_shippingcost",
    )

#Start of Products

class NewArrival(models.Model):
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class NewArrivalLanguage(models.Model):
    name = models.TextField(default="")
    description = models.TextField(null=True, blank=True, default="")
    newArrivalId = models.ForeignKey(
        NewArrival,
        on_delete=models.CASCADE,
        related_name="newarrival_newarrivallanguage",
    )
    languageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_newarrivallanguage"
    )


class Item(models.Model):
    keyName = models.TextField(default="")
    isApproved = models.BooleanField(default=False)
    isTop = models.BooleanField(default=False)
    isFavorite = models.BooleanField(default=False)
    isMostDiscount = models.BooleanField(default=False)
    isMostViewed = models.BooleanField(default=False)
    isNewArrival = models.BooleanField(default=False)
    isElectronic = models.BooleanField(default=False)
    totalViews = models.IntegerField(default=0)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    departmentId = models.ForeignKey(
        Department, on_delete=models.CASCADE, related_name="department_item"
    )
    brandId = models.ForeignKey(
        Brand,
        on_delete=models.CASCADE,
        related_name="brand_item",
    )
    supplierId = models.ForeignKey(
        Supplier, on_delete=models.CASCADE, related_name="supplier_item"
    )
    newArrivalId = models.ForeignKey(
        NewArrival, on_delete=models.CASCADE, related_name="newarrival_item"
    )

class ItemLanguage(models.Model):
    name = models.TextField(default="")
    description = models.TextField(null=True, blank=True, default="")
    itemId = models.ForeignKey(
        Item, on_delete=models.CASCADE, related_name="item_itemlanguage"
    )
    languageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_itemlanguage"
    )

class FeatureBullet(models.Model):
    keyName = models.TextField(default="", null=True, blank=True)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    itemId = models.ForeignKey(
        Item, on_delete=models.CASCADE, related_name="item_featurebullet"
    )

class FeatureBulletLanguage(models.Model):
    description = models.TextField(null=True, blank=True, default="")
    featureBulletId = models.ForeignKey(
        FeatureBullet,
        on_delete=models.CASCADE,
        related_name="featurebullet_featurebulletlanguage",
    )
    languageId = models.ForeignKey(
        Language,
        on_delete=models.CASCADE,
        related_name="language_featurebulletlanguage",
    )

class Eligible(models.Model):
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    itemId = models.ForeignKey(
        Item, on_delete=models.CASCADE, related_name="item_eligable"
    )
    eligibleTypeId = models.ForeignKey(
        EligibleType, on_delete=models.CASCADE, related_name="eligibletype_eligible"
    )

class SKU(models.Model):
    keyName = models.TextField(default="")
    name = models.TextField(default="")
    price = models.FloatField(default=0)
    discount = models.FloatField(default=0)
    amount = models.FloatField(default=0)
    isTop = models.BooleanField(default=False)
    isFavorite = models.BooleanField(default=False)
    isMostDiscount = models.BooleanField(default=False)
    isMostViewed = models.BooleanField(default=False)
    isNewArrival = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    itemId = models.ForeignKey(Item, on_delete=models.CASCADE, related_name="item_sku")

class SKUImage(models.Model):
    keyName = models.TextField(default="")
    isDownloaded = models.BooleanField(default=False)
    fileName = models.TextField(default="",blank=True,null=True)
    extension = models.TextField(default="",blank=True,null=True)
    source = models.URLField(default="",blank=True,null=True)
    image = models.FileField(upload_to=sku_picture_path, null=True, blank=True, default="/default/holder.jpg")
    skuId = models.ForeignKey(SKU, on_delete=models.CASCADE, related_name="sku_skuimage")
    
    def save(self, *args, **kwargs):
        if self.pk is None:
            saved_image = self.image
            self.image = None
            super(SKUImage, self).save(*args, **kwargs)
            self.image = saved_image
            if "force_insert" in kwargs:
                kwargs.pop("force_insert")

        super(SKUImage, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        if self.image and hasattr(self.image,'url'):
            if self.image.url != "/media/default/holder.jpg":
                self.image.delete()
        super().delete()

class SKUOption(models.Model):
    keyName = models.TextField()
    isColor = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    skuId = models.ForeignKey(
        SKU, on_delete=models.CASCADE, related_name="sku_skuoption"
    )

class SKUOptionLanguage(models.Model):
    title = models.TextField(default="")
    value = models.TextField(default="")
    colorName = models.TextField(default="", blank=True, null=True)
    skuOptionId = models.ForeignKey(
        SKUOption, on_delete=models.CASCADE, related_name="skuoption_skuoptionlanguage"
    )
    languageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_skuoptionlanguage"
    )

class SKUDescription(models.Model):
    keyName = models.TextField(default="")
    isColor = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    skuId = models.ForeignKey(
        SKU, on_delete=models.CASCADE, related_name="sku_skudescription"
    )

class SKUDescriptionLanguage(models.Model):
    title = models.TextField(default="")
    value = models.TextField(default="")
    colorName = models.TextField(default="", blank=True, null=True)
    skuDescriptionId = models.ForeignKey(
        SKUDescription,
        on_delete=models.CASCADE,
        related_name="skudescription_skudescriptionlanguage",
    )
    languageId = models.ForeignKey(
        Language,
        on_delete=models.CASCADE,
        related_name="language_skudescriptionlanguage",
    )

#End of Products

# Start of orders
class Coupon(models.Model):
    code = models.TextField(default="")
    discount = models.FloatField(default=0)
    startDate = models.DateTimeField()
    endDate = models.DateTimeField()
    description = models.TextField(null=True, blank=True, default="")
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

    def __str__(self):
        return str(self.code)


class ShoppingCart(models.Model):
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    clientId = models.OneToOneField(
        Client,
        on_delete=models.CASCADE,
        primary_key=True,
        related_name="client_shoppingCart",
    )

class ShoppingCartItem(models.Model):
    quantity = models.FloatField(default=0)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    skuId = models.ForeignKey(
        SKU, on_delete=models.CASCADE, related_name="sku_shoppingcartitem"
    )
    shoppingCartId = models.ForeignKey(
        ShoppingCart,
        on_delete=models.CASCADE,
        related_name="shoppingcart_shoppingcartitem",
    )

class PurchaseOrder(models.Model):
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    isCanceled = models.BooleanField(default=False)
    isRefunded = models.BooleanField(default=False)
    paymentMethodId = models.ForeignKey(
        PaymentMethod,
        on_delete=models.CASCADE,
        related_name="paymentmethod_purchaseorder",
    )
    orderFromId = models.ForeignKey(
        OrderFrom, on_delete=models.CASCADE, related_name="orderfrom_purchaseorder"
    )
    couponId = models.ForeignKey(
        Coupon,
        on_delete=models.CASCADE,
        related_name="coupon_purchaseorder",
        null=True,
        blank=True,
    )
    clientId = models.ForeignKey(
        Client, on_delete=models.CASCADE, related_name="client_purchaseorder"
    )

class ShippingItem(models.Model):
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    isValidAndPaid = models.BooleanField(default=False)
    shippingCostId = models.ForeignKey(
        ShippingCost,
        on_delete=models.CASCADE,
        related_name="shippingcost_shippingitem",
        null=True
    )
    purchaseOrderId = models.ForeignKey(
        PurchaseOrder,
        on_delete=models.CASCADE,
        related_name="purchaseorder_shippingitem",
    )

class ShippingAddress(models.Model):
    trackNumber = models.TextField(blank=True, null=True, default="")
    address1 = models.TextField(default="")
    address2 = models.TextField(default="")
    zipCode = models.TextField(default="")
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    countryId = models.ForeignKey(
        Country, on_delete=models.CASCADE, related_name="country_shippingaddress"
    )
    stateId = models.ForeignKey(
        State,
        on_delete=models.CASCADE,
        related_name="state_shippingaddress",
        null=True,
        blank=True,
    )
    cityId = models.ForeignKey(
        City,
        on_delete=models.CASCADE,
        related_name="city_shippingaddress",
        null=True,
        blank=True,
    )
    shippingItemId = models.OneToOneField(
        ShippingItem,
        on_delete=models.CASCADE,
        primary_key=True,
        related_name="shippingitem_ShippingAddress",
    )

    def __str__(self):
        return str(self.shippingItemId)

class PurchaseShippingItem(models.Model):
    skuPrice = models.FloatField(default=0)
    skuDiscount = models.FloatField(default=0)
    deliveredQuantity = models.FloatField(default=0)
    returnedQuantity = models.FloatField(default=0)
    canceledQuantity = models.FloatField(default=0)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    skuCostId = models.ForeignKey(
        SKUCost, on_delete=models.CASCADE, related_name="skucost_purchaseshippingitem"
    )
    skuId = models.ForeignKey(
        SKU, on_delete=models.CASCADE, related_name="sku_purchaseshippingitem"
    )
    shippingItemId = models.ForeignKey(
        ShippingItem,
        on_delete=models.CASCADE,
        related_name="shppingitem_purchaseshippingitem",
    )

class RequestReturn(models.Model):
    headLine = models.TextField(default="")
    requestedQuantity = models.FloatField(default=0)
    issue = models.TextField(default="")
    note = models.TextField(null=True, blank=True, default="")
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    returnStatusId = models.ForeignKey(
        ReturnStatus,
        on_delete=models.CASCADE,
        related_name="returnstatus_requestreturn",
    )
    purchaseShippingItemId = models.ForeignKey(
        PurchaseShippingItem,
        on_delete=models.CASCADE,
        related_name="purchaseshippingitem_requestreturn",
    )


class Track(models.Model):
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    shippingAddressId = models.ForeignKey(
        ShippingAddress, on_delete=models.CASCADE, related_name="shippingaddress_track"
    )
    trackStatusId = models.ForeignKey(
        TrackStatus, on_delete=models.CASCADE, related_name="trackstatus_track"
    )


class SalesOrder(models.Model):
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    isConfirmed = models.BooleanField(default=False)
    supplierId = models.ForeignKey(
        Supplier, on_delete=models.CASCADE, related_name="supplier_salesorder"
    )
    shippingItemId = models.OneToOneField(
        ShippingItem,
        on_delete=models.CASCADE,
        primary_key=True,
        related_name="shippingitem_salesorder",
    )

class SalesOrderItem(models.Model):
    quantity = models.FloatField(default=0)
    price = models.FloatField(default=0)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    skuId = models.ForeignKey(
        SKU, on_delete=models.CASCADE, related_name="sku_salesorderitem"
    )
    salesOrderId = models.ForeignKey(
        SalesOrder, on_delete=models.CASCADE, related_name="salesorder_salesorderitem"
    )


# End of Orders


class ItemSubscription(models.Model):
    price = models.FloatField(default=0)
    discount = models.FloatField(default=0)
    serviceCost = models.FloatField(default=0)
    startDate = models.DateTimeField()
    endDate = models.DateTimeField()
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    itemId = models.ForeignKey(
        Item, on_delete=models.CASCADE, related_name="item_itemsubscription"
    )
    subscriptionTypeId = models.ForeignKey(
        SubscriptionType,
        on_delete=models.CASCADE,
        related_name="subscriptiontype_itemsubscription",
    )
    subscriptionStatusId = models.ForeignKey(
        SubscriptionStatus,
        on_delete=models.CASCADE,
        related_name="subscriptionstatus_itemsubscription",
    )


class Favorite(models.Model):
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    itemId = models.ForeignKey(
        Item, on_delete=models.CASCADE, related_name="item_favorite"
    )
    clientId = models.ForeignKey(
        Client, on_delete=models.CASCADE, related_name="client_favorite"
    )


class ClientItemRateReview(models.Model):
    headLine = models.TextField(default="")
    rate = models.FloatField(default=0)
    comment = models.TextField(default="")
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    itemId = models.ForeignKey(
        Item, on_delete=models.CASCADE, related_name="item_client_rate_review"
    )
    clientId = models.ForeignKey(
        Client, on_delete=models.CASCADE, related_name="client_item_rate_review"
    )


class ClientSupplierRateReview(models.Model):
    headLine = models.TextField(default="")
    rate = models.FloatField(default=0)
    comment = models.TextField(default="")
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    supplierId = models.ForeignKey(
        Supplier, on_delete=models.CASCADE, related_name="supplier_client_rate_review"
    )
    clientId = models.ForeignKey(
        Client, on_delete=models.CASCADE, related_name="client_supplier_rate_review"
    )


# Start of Feedback
class Feedback(models.Model):
    headLine = models.TextField(default="")
    rate = models.FloatField(default=0)
    comment = models.TextField(default="")
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    clientId = models.ForeignKey(
        Client, on_delete=models.CASCADE, related_name="client_feedback"
    )

    def __str__(self):
        return str(self.id)


class Request(models.Model):
    headLine = models.TextField(default="")
    description = models.TextField(default="")
    response = models.TextField(blank=True, null=True, default="")
    isDone = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    clientId = models.ForeignKey(
        Client, on_delete=models.CASCADE, related_name="client_request"
    )


# End of Feedback

# Start of Policy
class PolicyType(models.Model):
    name = models.TextField(default="")
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class PolicyHeader(models.Model):
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    policyTypeId = models.ForeignKey(
        PolicyType, on_delete=models.CASCADE, related_name="policytype_policyheader"
    )

class PolicyHeaderLanguage(models.Model):
    name = models.TextField(default="")
    policyHeaderId = models.ForeignKey(
        PolicyHeader,
        on_delete=models.CASCADE,
        related_name="policyheader_policyheaderlanguage",
    )
    languageId = models.ForeignKey(
        Language, on_delete=models.CASCADE, related_name="language_policyheaderlanguage"
    )

class PolicyDescription(models.Model):
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    policyHeaderId = models.ForeignKey(
        PolicyHeader,
        on_delete=models.CASCADE,
        related_name="policyheader_policydescription",
    )

class PolicyDescriptionLanguage(models.Model):
    description = models.TextField(default="")
    policyDescriptionId = models.ForeignKey(
        PolicyDescription,
        on_delete=models.CASCADE,
        related_name="policydescription_policydescriptionlanguage",
    )
    languageId = models.ForeignKey(
        Language,
        on_delete=models.CASCADE,
        related_name="language_policydescriptionlanguage",
    )


# End of Policy

class RechargeCost(models.Model):
    serviceCost = models.FloatField(default=0)
    taxCost = models.FloatField(default=0)
    transactionFixedCost = models.FloatField(default=0)
    transactionFeeCost = models.FloatField(default=0)
    isEnabled = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

    def __str__(self):
        return str(self.id)

# Start of Transaction Model

class Recharge(models.Model):
    subTotal = models.FloatField(default=0)
    sessionId = models.TextField(null=True, blank=True, default="")
    paymentIntentId = models.TextField(null=True, blank=True, default="")
    description = models.TextField(null=True, blank=True, default="")
    rechargeCostId = models.ForeignKey(
        RechargeCost,
        on_delete=models.CASCADE,
        related_name="rechargecost_recharge",
        null=True,
        blank=True,
    )
    paymentMethodId = models.ForeignKey(
        PaymentMethod, on_delete=models.CASCADE, related_name="paymentmethod_recharge"
    )
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class Payment(models.Model):
    paid = models.FloatField(default=0)
    change = models.FloatField(default=0)
    total = models.FloatField(default=0)
    taxCost = models.FloatField(default=0)
    salesOrderCost = models.FloatField(default=0)
    deliveryCost = models.FloatField(default=0)
    returnCost = models.FloatField(default=0)
    rechargeCost = models.FloatField(default=0)
    description = models.TextField(null=True, blank=True, default="")
    descriptionDetail = models.TextField(null=True, blank=True, default="")
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    transactionTypeId = models.ForeignKey(
        TransactionType,
        on_delete=models.CASCADE,
        related_name="transaction_payment",
        null=True,
        blank=True,
    )
    purchaseOrderId = models.ForeignKey(
        PurchaseOrder,
        on_delete=models.SET_NULL,
        related_name="purchaseorder_payment",
        null=True,
        blank=True,
    )
    subscriptionId = models.ForeignKey(
        Subscription,
        on_delete=models.SET_NULL,
        related_name="subscription_payment",
        null=True,
        blank=True,
    )
    rechargeId = models.ForeignKey(
        Recharge,
        on_delete=models.SET_NULL,
        related_name="recharge_payment",
        null=True,
        blank=True,
    )

    # taxesId = models.ForeignKey(
    #     Taxes,
    #     on_delete=models.CASCADE,
    #     related_name="taxes_payment",
    #     null=True,
    #     blank=True,
    # )
    # salesOrderId = models.ForeignKey(
    #     SalesOrder,
    #     on_delete=models.SET_NULL,
    #     related_name="salesorder_payment",
    #     null=True,
    #     blank=True,
    # )
    # deliveryManId = models.ForeignKey(
    #     DeliveryMan,
    #     on_delete=models.SET_NULL,
    #     related_name="deliveryman_payment",
    #     null=True,
    #     blank=True,
    # )
    # requestReturnId = models.ForeignKey(
    #     RequestReturn,
    #     on_delete=models.SET_NULL,
    #     related_name="requestreturn_payment",
    #     null=True,
    #     blank=True,
    # )

    # itemSubscriptionId = models.ForeignKey(
    #     ItemSubscription,
    #     on_delete=models.SET_NULL,
    #     related_name="itemsubscription_payment",
    #     null=True,
    #     blank=True,
    # )


#Start of Accessory
class Accessory(models.Model):
    name = models.TextField(default="")
    price = models.FloatField(default=0)
    description = models.TextField(null=True, blank=True, default="")
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class AccessoryTransaction(models.Model):
    quantity = models.IntegerField(default=0)
    price = models.FloatField(default=0)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    transactionTypeId = models.ForeignKey(
        TransactionType,
        on_delete=models.CASCADE,
        related_name="transactiontype_AccessoryTransaction",
    )
    accessoryId = models.ForeignKey(
        Accessory,
        on_delete=models.CASCADE,
        related_name="Accessory_AccessoryTransaction",
    )


class Employee(models.Model):
    fullName = models.TextField(default="")
    email = models.TextField(default="")
    password = models.CharField(max_length=50, null=True, blank=True)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

    def __str__(self):
        return str(self.fullName)

#Start of System Traffic
class SystemTraffic(models.Model):
    country = models.TextField(default="", null=True, blank=True)
    state = models.TextField(default="", null=True, blank=True)
    city = models.TextField(default="", null=True, blank=True)
    latitude = models.FloatField(default=0, null=True, blank=True)
    longitude = models.FloatField(default=0, null=True, blank=True)
    deviceIP = models.TextField(default="", null=True, blank=True)
    openFrom = models.TextField(default="", null=True, blank=True)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
#End of System Traffic