from django.db import models, transaction

from oscar.core.loading import get_model

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


def delete_broken_file_attributes():
    "A lot of the file attributes got save without any file present, which causes errors"
    output = "Broken file and image attributes where successfully deleted files: %i %s images: %i %s"
    with transaction.atomic():
        broken_files = ProductAttributeValue.objects.filter(
            models.Q(value_file__isnull=True) | models.Q(value_file=""),
            attribute__type=ProductAttribute.FILE,
        )
        broken_images = ProductAttributeValue.objects.filter(
            models.Q(value_image__isnull=True) | models.Q(value_image=""),
            attribute__type=ProductAttribute.IMAGE,
        )
        return output % (broken_files.delete() + broken_images.delete())
