from collections import OrderedDict

from django.conf import settings
from django.db import models
from wagtail.documents.models import AbstractDocument, Document
from wagtail.images.models import AbstractImage, AbstractRendition, Image


class CustomImage(AbstractImage):
    alt_text = models.TextField(blank=True)

    admin_form_fields = Image.admin_form_fields + ("alt_text",)

    @property
    def default_alt_text(self):
        return self.alt_text


class CustomRendition(AbstractRendition):
    image = models.ForeignKey(CustomImage, on_delete=models.CASCADE, related_name="renditions")

    class Meta:
        unique_together = (("image", "filter_spec", "focal_point_key"),)

    @property
    def attrs_dict(self):
        """
        A dict of the src, width, height, and alt attributes for an <img> tag.
        This fix <img src="" /> generated by RichTextBlocks.
        """
        return OrderedDict(
            [
                ("src", self.full_url),
                ("width", self.width),
                ("height", self.height),
                ("alt", self.alt),
            ]
        )


class CustomDocument(AbstractDocument):
    admin_form_fields = Document.admin_form_fields

    @property
    def url(self):
        """
        Property based on image AbstractRendition.full_url property.
        """
        url = super().url
        if hasattr(settings, "WAGTAILADMIN_BASE_URL") and url.startswith("/"):
            url = settings.WAGTAILADMIN_BASE_URL + url
        return url
