"""
Clean up all <font> and style= and things that mess up the styling from
rich text fields.
"""

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

from oscar.core.loading import get_model

from ocyan.main.templatetags.ocyan_main import stripformatting
from ocyan.main.utils import disable_searchengine_updates

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


class Command(BaseCommand):
    help = __doc__

    def handle(self, *args, **options):
        with disable_searchengine_updates():
            for p in Product.objects.all():
                p.description = stripformatting(p.description)
                p.long_description = (
                    stripformatting(p.long_description)
                    if p.long_description is not None
                    else None
                )
                p.save()
            for pa in ProductAttributeValue.objects.filter(
                attribute__type=ProductAttribute.RICHTEXT
            ):
                pa.value_richtext = (
                    stripformatting(pa.value_richtext)
                    if pa.value_richtext is not None
                    else None
                )
                pa.save()
            for c in Category.objects.all():
                c.description = stripformatting(c.description)
                c.save()

        call_command("update_oscar_index")
