from django.db.models.signals import post_save, post_delete, m2m_changed
from django.dispatch import receiver
from django.core.cache import cache
from home.models import (Home, AboutMe, MyService, MyServiceTitle, MyResume, Education, Experience, Skill, Knowledge,
                         MainMenu, Tags)

HOME_CACHE_KEYS = (
    'home:active_home',
    'home:active_aboutme',
    'home:service_list',
    'home:service_title',
    'home:resume',
    'home:education_list',
    'home:experience_list',
    'home:skill_list',
    'home:knowledge_list',
    'home:active_menu',
)


def clear_home_cache():
    cache.delete_many(HOME_CACHE_KEYS)


@receiver(post_save, sender=Home)
@receiver(post_delete, sender=Home)
@receiver(post_save, sender=AboutMe)
@receiver(post_delete, sender=AboutMe)
@receiver(post_save, sender=MyService)
@receiver(post_delete, sender=MyService)
@receiver(post_save, sender=MyServiceTitle)
@receiver(post_delete, sender=MyServiceTitle)
@receiver(post_save, sender=MyResume)
@receiver(post_delete, sender=MyResume)
@receiver(post_save, sender=Education)
@receiver(post_delete, sender=Education)
@receiver(post_save, sender=Experience)
@receiver(post_delete, sender=Experience)
@receiver(post_save, sender=Skill)
@receiver(post_delete, sender=Skill)
@receiver(post_save, sender=Knowledge)
@receiver(post_delete, sender=Knowledge)
@receiver(post_save, sender=MainMenu)
@receiver(post_delete, sender=MainMenu)
def clear_home_cache_on_save(sender, instance, **kwargs):
    clear_home_cache()


@receiver(m2m_changed, sender=Home.tags.through)
def clear_home_cache_on_tags_change(sender, instance, action, **kwargs):
    if action in {"post_add", "post_remove", "post_clear"}:
        clear_home_cache()
