from django.core.management.base import BaseCommand

from oscar.core.loading import get_model

ProductAttributeValue = get_model("catalogue", "ProductAttributeValue")
ProductAttribute = get_model("catalogue", "ProductAttribute")


class Command(BaseCommand):
    def add_arguments(self, parser):
        # Positional arguments
        parser.add_argument("product_class_slugs", nargs="*", type=str)

    def handle(self, *args, **options):
        product_class_slugs = options.get("product_class_slugs")

        attributes = ProductAttribute.objects.filter(
            type__in=[ProductAttribute.OPTION, ProductAttribute.MULTI_OPTION]
        )
        if product_class_slugs:
            attributes = attributes.filter(product_class__slug__in=product_class_slugs)

        all_values = []
        for option_attribute in ProductAttribute.objects.filter(
            type__in=[ProductAttribute.OPTION, ProductAttribute.MULTI_OPTION]
        ):
            values = ProductAttributeValue.objects.filter(attribute=option_attribute)
            for value in values:
                value.value_text = value.value_as_text
                all_values.append(value)
            option_attribute.type = ProductAttribute.TEXT
            option_attribute.save()

        ProductAttributeValue.objects.bulk_update(all_values, fields=["value_text"])
