from django.core.cache import cache
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

from .models import Publication, PublicationCategory
from .views import PUBLICATIONS_AUTHORS_CACHE_KEY, PUBLICATION_CATEGORY_STATS_KEY


@receiver([post_save, post_delete], sender=Publication)
def _bust_publication_caches(sender, instance, **kwargs):
    cache.delete(PUBLICATIONS_AUTHORS_CACHE_KEY)
    if instance.category_id:
        cache.delete(PUBLICATION_CATEGORY_STATS_KEY.format(id=instance.category_id))


@receiver([post_save, post_delete], sender=PublicationCategory)
def _bust_category_stats(sender, instance, **kwargs):
    cache.delete(PUBLICATION_CATEGORY_STATS_KEY.format(id=instance.id))
