from django.db import models
import os

from rm_gallery_api.settings import MEDIA_ROOT

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

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 department_picture_path(instance, filename):
    ext = filename.split('.')
    return os.path.join('departments/department_'+str(instance.id),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 newArrival_picture_path(instance, filename):
    ext = filename.split('.')
    return os.path.join('newarrivals/newarrival_'+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])

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

# Start Basic Data

class Settings(models.Model):
    isMaintenanceClient = models.BooleanField()
    isMaintenanceSupplier = models.BooleanField()
    isEnableFreeSubscriptionForSupplier = models.BooleanField()
    itemSKULimit = models.IntegerField()
    itemSKUOptionLimit = models.IntegerField()
    itemFeatureBulletLimit = models.IntegerField()
    maxCartQuantity = models.IntegerField()
    isUseStandardShipping = models.BooleanField()
    isUseZoneShipping = models.BooleanField()
    isUseAddressSelection = models.BooleanField()
    isUseAddressManually = models.BooleanField()
    isEnableStoreBankCards = models.BooleanField()
    isUseTaxes = models.BooleanField()
    isInitialSettingsDone = models.BooleanField()
    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 AppContent(models.Model):
    keyName = models.CharField(default='',max_length=10)
    description = models.TextField(default='')
    isSliderFlag = models.BooleanField(default=False)
    navigateTo = models.TextField(null=True, blank=True,default='')
    isUseItemImageLink = models.BooleanField(default=False)
    isUrl = 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.url != '/rmmedia/default/slider_holder.jpg':
            self.image.delete()
        super().delete()

class SocialLink(models.Model):
    keyName = models.CharField(default='',max_length=100)
    url = models.TextField(default='')
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    def __str__(self):
        return str(self.keyName)

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

class ProviderLanguage(models.Model):
    name = models.TextField(default='')
    providerId = models.ForeignKey(Provider, on_delete=models.CASCADE, related_name='provider_providerlanguage')
    languageId = models.ForeignKey(Language, on_delete=models.CASCADE, related_name='language_providerlanguage')

class ItemCost(models.Model):
    priceInPercent = models.FloatField()
    minPrice = models.FloatField()
    maxPrice = models.FloatField()
    isEnabled = models.BooleanField()
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    def __str__(self):
        return str(self.priceInPercent)

class Fees(models.Model):
    handlingFees = models.FloatField()
    packingFees = models.FloatField()
    isEnabled = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class Taxes(models.Model):
    price = models.FloatField()
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    def __str__(self):
        return str(self.price)

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 CancelType(models.Model):
    keyName = models.CharField(default='',max_length=100)
    price = models.FloatField()
    isPercentage = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class CancelTypeLanguage(models.Model):
    name = models.TextField(default='')
    cancelTypeId = models.ForeignKey(CancelType, on_delete=models.CASCADE, related_name='canceltype_canceltypelanguage')
    languageId = models.ForeignKey(Language, on_delete=models.CASCADE, related_name='language_canceltypelanguage')

class ReturnCost(models.Model):
    cost = models.FloatField()
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

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):
    description = 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 PaymentMethod(models.Model):
    keyName = models.CharField(default='',max_length=100)
    fixedPrice = models.FloatField(default=0)
    price = models.FloatField()
    isPercentage = models.BooleanField(default=False)
    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 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')

class Country(models.Model):
    isActive = models.BooleanField()
    isMainBranch = models.BooleanField()
    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 City(models.Model):
    isActive = models.BooleanField()
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    countryId = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='country_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')

class Zone(models.Model):
    isActive = models.BooleanField()
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    cityId = models.ForeignKey(City, on_delete=models.CASCADE, related_name='city_zone')

class ZoneLanguage(models.Model):
    name = models.TextField(default='')
    zoneId = models.ForeignKey(Zone, on_delete=models.CASCADE, related_name='zone_zonelanguage')
    languageId = models.ForeignKey(Language, on_delete=models.CASCADE, related_name='language_zonelanguage')

class District(models.Model):
    isActive = models.BooleanField()
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    zoneId = models.ForeignKey(Zone, on_delete=models.CASCADE, related_name='zone_district')

class DistrictLanguage(models.Model):
    name = models.TextField(default='')
    districtId = models.ForeignKey(District, on_delete=models.CASCADE, related_name='district_districtlanguage')
    languageId = models.ForeignKey(Language, on_delete=models.CASCADE, related_name='language_districtlanguage')

class DistrictPrice:
    def __init__(
        self,
        deliveryPriceId,
        countryId,
        country, 
        cityId,
        city,
        zoneId,
        zone,
        districtId,
        district,
        price,
        ):
        self.deliveryPriceId = deliveryPriceId
        self.countryId = countryId
        self.country = country
        self.cityId = cityId
        self.city = city
        self.zoneId = zoneId
        self.zone = zone
        self.districtId = districtId
        self.district = district
        self.price = price

class AllDistrictData:
    def __init__(
        self,
        countryId,
        country, 
        cityId,
        city,
        zoneId,
        zone,
        districtId,
        district,
        ):
        self.countryId = countryId
        self.country = country
        self.cityId = cityId
        self.city = city
        self.zoneId = zoneId
        self.zone = zone
        self.districtId = districtId
        self.district = district

class DeliveryPrice(models.Model):
    name = models.TextField(default='')
    upToWeight = models.FloatField()
    price = models.FloatField()
    additionalWeight = models.FloatField()
    additionalWeightPrice = models.FloatField()
    isInternal = models.BooleanField()
    isStandard = models.BooleanField()
    isEnabled = models.BooleanField(default=False)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    def __str__(self):
        return str(self.id)

class DeliveryPriceCityZone(models.Model):
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    deliveryPriceId = models.ForeignKey(DeliveryPrice, on_delete=models.CASCADE, related_name='deliveryprice_deliverypricecityzone')
    cityId = models.ForeignKey(City, on_delete=models.CASCADE, related_name='city_deliverypricecityzone')
    zoneId = models.ForeignKey(Zone, on_delete=models.SET_NULL, related_name='zone_deliverypricecityzone',null=True, blank=True)

class Department(models.Model):
    keyName = models.TextField(default='')
    isSelected = models.BooleanField(default=False)
    isPopular = models.BooleanField(default=False)
    isVisible = models.BooleanField(default=False)
    isUseItemImageLink = models.BooleanField(default=False)
    totalViews = models.IntegerField()
    image = models.ImageField(upload_to=department_picture_path,null=True, blank=True,default='/default/holder.jpg')
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    departmentId = models.ForeignKey('self', on_delete=models.CASCADE, related_name='department_subdepartment', blank=True, null=True)
    
    def save(self, *args, **kwargs):
        if self.pk is None:
            saved_image = self.image
            self.image = None
            super(Department, self).save(*args, **kwargs)
            self.image = saved_image
            if 'force_insert' in kwargs:
                kwargs.pop('force_insert')

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

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

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='')
    image = models.ImageField(upload_to=brand_picture_path,null=True, blank=True, default='/default/holder.jpg')
    isVisible = models.BooleanField(default=False)
    isUseItemImageLink = models.BooleanField(default=False)
    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.url != '/rmmedia/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')

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')

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')

class SubscriptionType(models.Model):
    costPerMonth = models.FloatField()
    price = models.FloatField()
    discount = models.FloatField()
    serviceCost = models.FloatField()
    durationInMonth = models.IntegerField()
    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 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 NewArrival(models.Model):
    image = models.ImageField(upload_to=newArrival_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(NewArrival, self).save(*args, **kwargs)
            self.image = saved_image
            if 'force_insert' in kwargs:
                kwargs.pop('force_insert')

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

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

class NewArrivalLanguage(models.Model):
    name = models.TextField(default='')
    description = models.CharField(max_length=2000,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 LinkType(models.Model):
    name = models.TextField(default='')
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

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

class LinkStatusLanguage(models.Model):
    name = models.TextField(default='')
    linkStatusId = models.ForeignKey(LinkStatus, on_delete=models.CASCADE, related_name='linkstatus_linkstatuslanguage')
    languageId = models.ForeignKey(Language, on_delete=models.CASCADE, related_name='language_linkstatuslanguage')

# End Basic Data

class Coupon(models.Model):
    code = models.TextField(default='')
    discount = models.FloatField()
    startDate = models.DateTimeField()
    endDate = models.DateTimeField()
    description = models.TextField(default='')
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    def __str__(self):
        return str(self.code)

class Client(models.Model):
    firstName = models.CharField(max_length=500)
    lastName = models.CharField(max_length=500)
    email = models.TextField(null=True, blank=True,default='')
    password = models.CharField(max_length=50,null=True, blank=True)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    providerId = models.ForeignKey(Provider, on_delete=models.CASCADE, related_name='provider_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 ClientPhone(models.Model):
    phone = models.CharField(max_length=20)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    clientId = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='client_phone')
    def __str__(self):
        return str(self.id)

class ClientCreditCard(models.Model):
    holder = models.TextField()
    number = models.CharField(max_length=20)
    expireYear = models.IntegerField()
    expireMonth = models.IntegerField()
    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 ClientAddressBook(models.Model):
    streetName = models.TextField(default='', blank=True, null=True)
    buildingNumber = models.IntegerField(default=0)
    floorNumber = models.IntegerField(default=0)
    apartmentNumber = models.IntegerField(default=0)
    notes = models.TextField(default='', blank=True, null=True)
    districtId = models.ForeignKey(District, on_delete=models.CASCADE, related_name='district_clientaddressbook', null=True, blank=True)
    isManually = models.BooleanField(default=False)
    addressLine1 = models.TextField(default='', blank=True, null=True)
    addressLine2 = models.TextField(default='', blank=True, null=True)
    city = models.TextField(default='', blank=True, null=True)
    county = models.TextField(default='', blank=True, null=True)
    postCode = models.TextField(default='', blank=True, null=True)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    clientId = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='client_clientaddressbook')
    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()
    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 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 PurchaseOrder(models.Model):
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    sessionId = models.TextField(null=True,blank=True,default='')
    paymentIntentId = models.TextField(null=True,blank=True,default='')
    isCanceled = models.BooleanField(default=False)
    isRefunded = models.BooleanField(default=False)
    paymentMethodId = models.ForeignKey(PaymentMethod, on_delete=models.CASCADE, related_name='paymentmethod_purchaseorder')
    taxesId = models.ForeignKey(Taxes, on_delete=models.CASCADE, related_name='taxes_purchaseorder',null=True, blank=True)
    orderFromId = models.ForeignKey(OrderFrom, on_delete=models.CASCADE, related_name='orderfrom_purchaseorder')
    cancelTypeId = models.ForeignKey(CancelType, on_delete=models.CASCADE,null=True, blank=True, related_name='canceltype_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 Supplier(models.Model):
    name = models.TextField()
    email = models.TextField()
    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)
    districtId = models.ForeignKey(District, on_delete=models.CASCADE, related_name='district_supplier', null=True, blank=True)
    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()
    discount = models.FloatField()
    serviceCost = models.FloatField()
    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()
    email = models.TextField()
    password = models.CharField(max_length=50,null=True, blank=True)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    districtId = models.ForeignKey(District, on_delete=models.CASCADE, related_name='district_delivery', null=True, blank=True)
    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 DeliveryManPrice(models.Model):
    price = models.FloatField()
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    deliveryPriceId = models.ForeignKey(DeliveryPrice, on_delete=models.CASCADE, related_name='deliveryprice_deliverymanprice')
    deliveryManId = models.ForeignKey(DeliveryMan, on_delete=models.CASCADE, related_name='deliveryman_deliverymanprice')
    def __str__(self):
        return str(self.id)

class ShippingItem(models.Model):
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    isValidAndPaid = models.BooleanField(default=False)
    deliveryPriceId = models.ForeignKey(DeliveryPrice, on_delete=models.CASCADE, related_name='deliveryprice_shippingitem')
    feesId = models.ForeignKey(Fees, on_delete=models.CASCADE, related_name='fees_shippingitem')
    purchaseOrderId = models.ForeignKey(PurchaseOrder, on_delete=models.CASCADE, related_name='purchaseorder_shippingitem')

class ShippingAddress(models.Model):
    trackNumber = models.TextField(blank=True, null=True,default='')
    phone = models.CharField(default='',max_length=50)
    streetName = models.TextField(default='', blank=True, null=True)
    buildingNumber = models.IntegerField(default=0)
    floorNumber = models.IntegerField(default=0)
    apartmentNumber = models.IntegerField(default=0)
    notes = models.TextField(default='', blank=True, null=True)
    districtId = models.ForeignKey(District, on_delete=models.CASCADE, related_name='district_shippingaddress', null=True, blank=True)
    isManually = models.BooleanField(default=False)
    addressLine1 = models.TextField(default='', blank=True, null=True)
    addressLine2 = models.TextField(default='', blank=True, null=True)
    city = models.TextField(default='', blank=True, null=True)
    county = models.TextField(default='', blank=True, null=True)
    postCode = models.TextField(default='', blank=True, null=True)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    deliveryManId = models.ForeignKey(DeliveryMan, on_delete=models.CASCADE,blank=True, null=True, related_name='deliveryman_shippingaddress')
    shippingItemId = models.OneToOneField(ShippingItem, on_delete=models.CASCADE, primary_key=True, related_name='shippingitem_ShippingAddress')
    def __str__(self):
        return str(self.shippingItemId)

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 Externalink(models.Model):
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    linkTypeId = models.ForeignKey(LinkType, on_delete=models.CASCADE, related_name='linktype_externallink')
    supplierId = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name='supplier_externallink')
    linkStatusId = models.ForeignKey(LinkStatus, on_delete=models.CASCADE, related_name='linkstatus_externallink')

class ExternalLinkLanguage(models.Model):
    url = models.TextField(default='',null=True, blank=True)
    externalLinkId = models.ForeignKey(Externalink, on_delete=models.CASCADE, related_name='externallink_externallinklanguage')
    languageId = models.ForeignKey(Language, on_delete=models.CASCADE, related_name='language_linklanguage')

class Item(models.Model):
    keyName = models.TextField(default='',null=True, blank=True)
    isApproved = models.BooleanField()
    isTop = models.BooleanField()
    isFavorite = models.BooleanField()
    isElectronic = models.BooleanField()
    totalViews = models.IntegerField()
    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',null=True, blank=True)
    linkId = models.ForeignKey(Externalink, on_delete=models.SET_NULL, related_name='externallink_item',null=True, blank=True)

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')

#Add this table
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')
#Add this table

class SKU(models.Model):
    keyName = models.TextField(default='',null=True, blank=True)
    name = models.TextField(null=True,blank=True,default='')
    price = models.FloatField()
    discount = models.FloatField()
    amount = models.FloatField()
    image = models.FileField(upload_to=sku_picture_path,null=True, blank=True, default='/default/holder.jpg')
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    itemId = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='item_sku')
    
    def save(self, *args, **kwargs):
        if self.pk is None:
            saved_image = self.image
            self.image = None
            super(SKU, self).save(*args, **kwargs)
            self.image = saved_image
            if 'force_insert' in kwargs:
                kwargs.pop('force_insert')

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

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

class SKUOption(models.Model):
    keyName = models.TextField(default='',null=True, blank=True)
    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='',null=True,blank=True)
    value = models.TextField(default='',null=True,blank=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='',null=True, blank=True)
    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='',null=True,blank=True)
    value = models.TextField(default='',null=True,blank=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')

class ItemSubscription(models.Model):
    price = models.FloatField()
    discount = models.FloatField()
    serviceCost = models.FloatField()
    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 ShoppingCartItem(models.Model):
    quantity = models.FloatField()
    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 PurchaseShippingItem(models.Model):
    offeredPrice = models.FloatField()
    skuPrice = models.FloatField()
    skuDiscount = models.FloatField()
    deliveredQuantity = models.FloatField()
    returnedQuantity = models.FloatField()
    canceledQuantity = models.FloatField()
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    itemCostId = models.ForeignKey(ItemCost, on_delete=models.CASCADE, related_name='itemcost_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()
    issue = models.TextField(default='')
    note = models.TextField(null=True,blank=True,default='')
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    returnCostId = models.ForeignKey(ReturnCost, on_delete=models.CASCADE, related_name='returncost_requestreturn')
    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 SalesOrderItem(models.Model):
    quantity = models.FloatField()
    price = models.FloatField()
    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')

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()
    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()
    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')

class Feedback(models.Model):
    headLine = models.TextField(default='')
    rate = models.FloatField()
    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()
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    clientId = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='client_request')

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')

class Recharge(models.Model):
    subTotal = models.FloatField()
    service = 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='')
    taxesId = models.ForeignKey(Taxes, on_delete=models.CASCADE, related_name='taxes_recharge',null=True, blank=True)
    paymentMethodId = models.ForeignKey(PaymentMethod, on_delete=models.CASCADE, related_name='paymentmethod_recharge')
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

    # @property
    # def getTaxesIsPaid(self):
    #     return Payment.objects.filter(rechargeId = self.id).filter(taxesId = self.taxesId).count()

class Payment(models.Model):
    paid = models.FloatField()
    change = models.FloatField()
    total = models.FloatField()
    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)
    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)
    subscriptionId = models.ForeignKey(Subscription, on_delete=models.SET_NULL, related_name='subscription_payment',null=True, blank=True)
    itemSubscriptionId = models.ForeignKey(ItemSubscription, on_delete=models.SET_NULL, related_name='itemsubscription_payment',null=True, blank=True)
    rechargeId = models.ForeignKey(Recharge, on_delete=models.SET_NULL, related_name='recharge_payment',null=True, blank=True)

class Accessory(models.Model):
    name = models.TextField(default='')
    price = models.FloatField()
    description = models.TextField(null=True, blank=True,default='')
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()

class AccessoryTransaction(models.Model):
    quantity = models.IntegerField()
    price = models.FloatField()
    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()
    email = models.TextField()
    password = models.CharField(max_length=50,null=True, blank=True)
    createdDate = models.DateTimeField()
    updatedDate = models.DateTimeField()
    def __str__(self):
        return str(self.fullName)