from django.core.management.base import BaseCommand
from tqdm import tqdm

from location.models import WineOriginAddress
from product.models import Product
from transfer.models import Products
from transfer.serializers.product import ProductSerializer


class Command(BaseCommand):
    help = 'Add to product wine origin object.'

    def handle(self, *args, **kwarg):
        def get_product(old_id: int):
            if old_id:
                qs = Product.objects.filter(old_id=old_id)
                if qs.exists():
                    return qs.first()

        objects_to_create = []
        products = Products.objects.exclude(wine_region_id__isnull=True) \
                                   .values_list('id', 'wine_sub_region_id', 'wine_region_id')
        for old_id, wine_sub_region_id, wine_region_id in tqdm(products):
            product = get_product(old_id)
            if product:
                wine_sub_region = ProductSerializer.get_wine_sub_region(wine_sub_region_id)
                wine_region = ProductSerializer.get_wine_region(wine_region_id)
                if wine_region:
                    filters = {
                        'product': product,
                        'wine_region': wine_region}
                    wine_origin_address = WineOriginAddress(
                        product=product,
                        wine_region=wine_region)

                    if wine_sub_region:
                        filters.update({'wine_sub_region': wine_sub_region})
                        wine_origin_address.wine_sub_region = wine_sub_region

                    if not WineOriginAddress.objects.filter(**filters).exists():
                        objects_to_create.append(wine_origin_address)

        WineOriginAddress.objects.bulk_create(objects_to_create)
        self.stdout.write(self.style.WARNING(f'COUNT CREATED OBJECTS: {len(objects_to_create)}'))
