# -*- coding: utf-8 -*-
import datetime

from django.core.cache import cache
from django.conf import settings

from events.rest_framework_contrib.utils import get_validation_mixture_key


def post_save_invalidate_api_signal_handler(sender=None, instance=None, *args, **kwargs):
    if sender and instance and sender is not object:
        is_should = any([q.filter(id=instance.id).exists() for q in sender._meta._queryset_list])
    else:
        is_should = True

    if is_should:
        invalidate_api()


def post_delete_invalidate_api_signal_handler(sender=None, instance=None, *args, **kwargs):
    invalidate_api()


def invalidate_api():
    key = get_validation_mixture_key(api_name='/v1/')
    new_value = datetime.datetime.utcnow()
    cache.set(key, value=new_value, version=settings.CACHE_VERSIONS['internal_site'])
    cache.set(key, value=new_value, version=settings.CACHE_VERSIONS['external_site'])
