"""
Draftail / contentstate conversion
"""

from draftjs_exporter.dom import DOM

from wagtail.admin.rich_text.converters.html_to_contentstate import LinkElementHandler

from oscar.core.loading import get_model


def product_link_entity(props):
    return DOM.create_element(
        "a",
        {
            "linktype": "product",
            "id": props.get("id"),
        },
        props["children"],
    )


def category_link_entity(props):
    return DOM.create_element(
        "a",
        {
            "linktype": "category",
            "id": props.get("id"),
        },
        props["children"],
    )


class OscarLinkElementHandler(LinkElementHandler):
    def get_model(self):
        raise NotImplementedError

    def get_attribute_data(self, attrs):
        Model = self.get_model()
        try:
            _id = int(attrs["id"])
        except (KeyError, ValueError):
            return {}

        try:
            doc = Model.objects.get(id=_id)
        except Model.DoesNotExist:
            return {"id": _id}

        return {
            "id": doc.id,
            "url": doc.get_absolute_url(),
        }


class ProductLinkElementHandler(OscarLinkElementHandler):
    def get_model(self):
        return get_model("catalogue", "Product")


class CategoryLinkElementHandler(OscarLinkElementHandler):
    def get_model(self):
        return get_model("catalogue", "Category")


ContentstateProductLinkConversionRule = {
    "from_database_format": {
        'a[linktype="product"]': ProductLinkElementHandler("PRODUCT"),
    },
    "to_database_format": {"entity_decorators": {"PRODUCT": product_link_entity}},
}


ContentstateCategoryLinkConversionRule = {
    "from_database_format": {
        'a[linktype="category"]': CategoryLinkElementHandler("CATEGORY"),
    },
    "to_database_format": {"entity_decorators": {"CATEGORY": category_link_entity}},
}
