from django import template

from ocyan.core.utils import RequestLibrary

try:
    from unittest.mock import patch

    from oxyan.themes.models import PageMenuProxy

    # I don't want to rewrite the aweful code in category_tags.
    # but I can not import it because it depends on oscar.apps.catalogue.
    # So I monkey path get_model to remedy the issue.
    # maybe one day someone will write a specialized category_tree tag for
    # wagtail.

    class FakeField:
        def __init__(self, name):
            self.name = name

    class FakeMeta:
        def get_fields(self):
            return [
                FakeField("id"),
                FakeField("path"),
                FakeField("depth"),
                FakeField("numchild"),
                FakeField("name"),
                FakeField("title"),
                FakeField("slug"),
            ]

    class FakeCategory:
        _meta = FakeMeta()

        @staticmethod
        def get_tree():
            return PageMenuProxy.get_tree()

    with patch("oscar.core.loading.get_model", lambda _, __: FakeCategory):
        from oscar.templatetags.category_tags import (
            get_annotated_list,
        )

    register = template.Library()
    cached_library = RequestLibrary(register)
    cached_library.simple_tag(get_annotated_list, name="category_tree")

except ImportError:
    # pylint: disable=unused-argument
    def get_annotated_list(depth, parent):
        return []

    register = template.Library()
    cached_library = RequestLibrary(register)
    cached_library.simple_tag(get_annotated_list, name="category_tree")
