from django.core.management.base import BaseCommand

from location.models import WineOriginAddress, EstablishmentWineOriginAddress
from product.models import Product


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

    def handle(self, *args, **kwarg):
        create_counter = 0

        for product in Product.objects.exclude(establishment__isnull=True):
            establishment = product.establishment
            if product.wine_origins.exists():
                for wine_origin in product.wine_origins.all():
                    wine_region = wine_origin.wine_region
                    wine_sub_region = wine_origin.wine_sub_region
                    if not EstablishmentWineOriginAddress.objects.filter(establishment=establishment,
                                                                         wine_region=wine_region,
                                                                         wine_sub_region=wine_sub_region) \
                                                                 .exists():
                        EstablishmentWineOriginAddress.objects.create(
                            establishment=establishment,
                            wine_region=wine_origin.wine_region,
                            wine_sub_region=wine_origin.wine_sub_region,
                        )
                        create_counter += 1

        self.stdout.write(self.style.WARNING(f'COUNT CREATED OBJECTS: {create_counter}'))
