"""
editor-html conversion for contenteditable editors
"""

from django.utils.html import escape

from wagtail.admin.rich_text.converters import editor_html

from oscar.core.loading import get_model


class OscarModelLinkHandlerBase:
    linktype = None

    def get_model(self):
        raise NotImplementedError

    @staticmethod
    def get_db_attributes(tag):
        return {"id": tag["data-id"]}

    def expand_db_attributes(self, attrs):
        Model = self.get_model()
        try:
            prod = Model.objects.get(id=attrs["id"])
            return '<a data-linktype="%s" data-id="%d" href="%s">' % (
                self.linktype,
                prod.id,
                escape(prod.get_absolute_url()),
            )
        except Model.DoesNotExist:
            # Preserve the ID attribute for troubleshooting purposes, even though it
            # points to a missing document
            return '<a data-linktype="%s" data-id="%s">' % (self.linktype, attrs["id"])
        except KeyError:
            return '<a data-linktype="%s">' % self.linktype


class ProductLinkHandler(OscarModelLinkHandlerBase):
    linktype = "product"

    def get_model(self):
        return get_model("catalogue", "Product")


class CategoryLinkHandler(OscarModelLinkHandlerBase):
    linktype = "category"

    def get_model(self):
        return get_model("catalogue", "Category")


EditorHTMLProductLinkConversionRule = [
    editor_html.LinkTypeRule("product", ProductLinkHandler),
]


EditorHTMLCategoryLinkConversionRule = [
    editor_html.LinkTypeRule("category", CategoryLinkHandler),
]
