import string
import random
from apps.product import models as product_models
from apps.authentication.models import User
from apps.pos_device.models import Device
from apps.herd.models import Rancher
from apps.core.models import BaseModel
from django.db import models


class InventoryEntry(BaseModel):
    entry_identity = models.CharField(max_length=50, null=True)
    distribution = models.ForeignKey(
        product_models.QuotaDistribution,
        on_delete=models.CASCADE,
        related_name='inventory_entry',
        null=True
    )
    organization = models.ForeignKey(
        product_models.Organization,
        on_delete=models.CASCADE,
        related_name="inventory",
        null=True
    )
    weight = models.PositiveBigIntegerField(default=0)
    balance = models.PositiveBigIntegerField(default=0)
    lading_number = models.CharField(max_length=50, null=True)
    delivery_address = models.TextField(blank=True, null=True)
    document = models.CharField(max_length=250, null=True)
    is_confirmed = models.BooleanField(default=False)
    notes = models.TextField(blank=True, null=True)

    def generate_entry_identity(self):  # noqa
        """ generate identity for every device """
        # prefix = "POS"
        while True:
            number_part = ''.join(random.choices(string.digits, k=6))
            code = f"{self.distribution.quota.quota_id}{number_part}"
            if not InventoryEntry.objects.filter(entry_identity=code).exists():
                return code

    @property
    def total_sold(self):
        return self.inventory_sales.aggregate(total=models.Sum('weight'))['total'] or 0

    @property
    def remaining_weight(self):
        return self.weight - self.total_sold

    def __str__(self):
        return f"distribution: {self.distribution.distribution_id}-{self.organization.name}"

    def save(self, *args, **kwargs):
        if not self.entry_identity:
            self.entry_identity = self.generate_entry_identity()
        super(InventoryEntry, self).save(*args, **kwargs)


class InventoryQuotaSaleTransaction(BaseModel):
    rancher = models.ForeignKey(
        Rancher,
        on_delete=models.CASCADE,
        related_name='transactions',
        null=True
    )
    pos_device = models.ForeignKey(
        Device,
        on_delete=models.CASCADE,
        related_name='transactions',
        null=True
    )
    transaction_id = models.CharField(max_length=50, null=True)
    seller_organization = models.ForeignKey(
        product_models.Organization,
        on_delete=models.CASCADE,
        related_name='inventory_sales',
        null=True
    )
    quota_distribution = models.ForeignKey(
        product_models.QuotaDistribution,
        on_delete=models.CASCADE,
        related_name='inventory_sales',
        null=True
    )
    inventory_entry = models.ForeignKey(
        InventoryEntry,
        on_delete=models.CASCADE,
        related_name='inventory_sales',
        null=True
    )
    weight = models.DecimalField(max_digits=12, decimal_places=2, null=True)
    delivery_address = models.TextField(blank=True, null=True)
    product = models.ForeignKey(
        product_models.Product,
        on_delete=models.CASCADE,
        related_name='sale_transactions',
        null=True
    )
    transaction_price = models.PositiveBigIntegerField(default=0)
    price_paid = models.PositiveBigIntegerField(default=0)
    type_of_price = (
        ('card', 'CARD'),
        ('cash', 'CASH'),
        ('credit', 'CREDIT'),
        ('check', 'CHECK'),
    )
    price_type = models.CharField(choices=type_of_price, max_length=50, null=True)
    description = models.TextField(blank=True, null=True)
    herd_owners_number = models.PositiveBigIntegerField(default=0)
    transactions_number = models.PositiveBigIntegerField(default=0)
    status_type = (
        ('success', 'SUCCESS'),
        ('waiting', 'WAITING'),
        ('failed', 'Failed'),
    )
    transaction_status = models.CharField(choices=status_type, max_length=25, null=True)
    transaction_status_code = models.IntegerField(default=0)
    result_text = models.TextField(null=True)
    ref_num = models.CharField(max_length=50, null=True)
    terminal = models.CharField(max_length=50, null=True)
    payer_cart = models.CharField(max_length=50, null=True)
    additional = models.JSONField(default=dict)

    def buyers_count(self):
        """ number of buyers from specific inventory """

        unique_buyers_count = self.objects.filter(
            inventory_entry=self.inventory_entry
        ).values('buyer_user').distinct().count()

        return unique_buyers_count

    def __str__(self):
        return f"Inventory Sale: {self.transaction_id}-{self.quota_distribution.distribution_id}"

    def save(self, *args, **kwargs):
        super(InventoryQuotaSaleTransaction, self).save(*args, **kwargs)
