from django.contrib.sites.models import Site
from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.translation import get_language

from wagtail.signals import page_published, page_unpublished, post_page_move

from oscar.core.loading import get_model

OcyanSettings = get_model("ocyan_plugin_wagtail", "OcyanSettings")


def invalidate_key(key):
    cache.delete(make_template_fragment_key(key, vary_on=[get_language()]))
    cache.delete(make_template_fragment_key(key, vary_on=[get_language(), ""]))
    for site in Site.objects.all():
        cache.delete(make_template_fragment_key(key, vary_on=[get_language(), site]))


# pylint: disable=W0613
@receiver(post_page_move)
@receiver(page_unpublished)
@receiver(page_published)
def clear_header_page_menu(sender, **kwargs):
    invalidate_key("header_page_menu")


# pylint: disable=W0613
@receiver(post_save, sender=OcyanSettings)
def clear_footer_menu(sender, **kwargs):
    invalidate_key("footer_menu")


try:
    Category = get_model("catalogue", "Category")

    # pylint: disable=W0613
    @receiver(post_save, sender=Category)
    def clear_product_menu(sender, **kwargs):
        invalidate_key("header_product_menu")
        invalidate_key("header_mega_menu")

except (ImportError, LookupError):
    # no oscar in installed apps
    pass
