import structlog
from django.core.cache import caches
from django.db.models.signals import post_delete, post_save
from wagtail.models import Page

logger = structlog.get_logger(__name__)


def get_all_subclasses(cls):
    all_subclasses = []

    for subclass in cls.__subclasses__():
        all_subclasses.append(subclass)
        all_subclasses.extend(get_all_subclasses(subclass))

    return all_subclasses


def invalidate_api_page_cache(sender, **kwargs):
    logger.debug("invalidate api_page_cache", label="api_page_cache")
    caches["api_page_cache"].clear()


for subclass in get_all_subclasses(Page):
    post_save.connect(invalidate_api_page_cache, subclass)
    post_delete.connect(invalidate_api_page_cache, subclass)
