# Path: repowatcher/main/utils.py
# def expire_view_cache(view_name, args = [], kwargs={}, namespace=None, key_prefix=None):
#     """
#     This function allows you to invalidate any view-level cache. 
#         view_name: view function you wish to invalidate or it's named url pattern
#         args: any arguments passed to the view function
#         namepace: optioal, if an application namespace is needed
#         key prefix: for the @cache_page decorator for the function (if any)
#     """
# 
#     # create a fake request object
#     request = HttpRequest()
#     # Loookup the request path:
#     if namespace:
#         view_name = namespace + ":" + view_name
#     request.path = reverse(view_name, args = args, kwargs=kwargs)
#     # get cache key, expire if the cached item exists:
#     key = cache.make_key(get_cache_key(request, key_prefix=key_prefix))
#     if key:
#         if cache.get(key):
#             cache.delete(key)
#             return True
#     return False


from django.contrib.auth.models import User
from django.db import models
from django.db.models.fields import EmailField, URLField, CharField, TextField, \
    PositiveIntegerField, SlugField, DateTimeField, BooleanField
from django.db.models.fields.related import ForeignKey
from django.db.models.signals import post_save, pre_save
from repowatcher.main.utils import expire_view_cache
from social_auth.fields import JSONField
import hashlib
import logging
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

def expire_cache(sender, instance, **kwargs):
    try:
        github_username = None
        bitbucket_username = None
        try:
            github_username = instance.user.social_auth.get(provider='github').extra_data['username']
            github_prefix = github_username
        except:
            github_prefix = ''
        try:
            bitbucket_username = instance.user.social_auth.get(provider='bitbucket').extra_data['username']
            bitbucket_prefix=bitbucket_username
        except:
            bitbucket_prefix = ''
        custom_prefix = '.'.join((hashlib.md5(github_prefix).hexdigest(),hashlib.md5(bitbucket_prefix).hexdigest()))
        expire_view_cache('authed_owned', key_prefix=custom_prefix)
        expire_view_cache('authed_watched', key_prefix=custom_prefix)
        if github_username:
            expire_view_cache('github_username_owned', kwargs = {'username':github_username}, key_prefix=custom_prefix)
            expire_view_cache('github_username_watched', kwargs = {'username':github_username}, key_prefix=custom_prefix)
        if bitbucket_username:
            expire_view_cache('bitbucket_username_owned', kwargs = {'username':bitbucket_username}, key_prefix=custom_prefix)
            expire_view_cache('bitbucket_username_watched', kwargs = {'username':bitbucket_username}, key_prefix=custom_prefix)

        category_links = instance.userrepositorylink_set.order_by('repository_category').distinct('repository_category')
        for category_link in category_links:

# Path: repowatcher/main/utils.py
# def expire_view_cache(view_name, args = [], kwargs={}, namespace=None, key_prefix=None):
#     """
#     This function allows you to invalidate any view-level cache. 
#         view_name: view function you wish to invalidate or it's named url pattern
#         args: any arguments passed to the view function
#         namepace: optioal, if an application namespace is needed
#         key prefix: for the @cache_page decorator for the function (if any)
#     """
# 
#     # create a fake request object
#     request = HttpRequest()
#     # Loookup the request path:
#     if namespace:
#         view_name = namespace + ":" + view_name
#     request.path = reverse(view_name, args = args, kwargs=kwargs)
#     # get cache key, expire if the cached item exists:
#     key = cache.make_key(get_cache_key(request, key_prefix=key_prefix))
#     if key:
#         if cache.get(key):
#             cache.delete(key)
#             return True
#     return False


# Path: repowatcher/main/models.py
from django.contrib.auth.models import User
from django.db import models
from django.db.models.fields import EmailField, URLField, CharField, TextField, \
    PositiveIntegerField, SlugField, DateTimeField, BooleanField
from django.db.models.fields.related import ForeignKey
from django.db.models.signals import post_save, pre_save
from repowatcher.main.utils import expire_view_cache
from social_auth.fields import JSONField
import hashlib
import logging

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

def expire_cache(sender, instance, **kwargs):
    try:
        github_username = None
        bitbucket_username = None
        try:
            github_username = instance.user.social_auth.get(provider='github').extra_data['username']
            github_prefix = github_username
        except:
            github_prefix = ''
        try:
            bitbucket_username = instance.user.social_auth.get(provider='bitbucket').extra_data['username']
            bitbucket_prefix=bitbucket_username
        except:
            bitbucket_prefix = ''
        custom_prefix = '.'.join((hashlib.md5(github_prefix).hexdigest(),hashlib.md5(bitbucket_prefix).hexdigest()))
        expire_view_cache('authed_owned', key_prefix=custom_prefix)
        expire_view_cache('authed_watched', key_prefix=custom_prefix)
        if github_username:
            expire_view_cache('github_username_owned', kwargs = {'username':github_username}, key_prefix=custom_prefix)
            expire_view_cache('github_username_watched', kwargs = {'username':github_username}, key_prefix=custom_prefix)
        if bitbucket_username:
            expire_view_cache('bitbucket_username_owned', kwargs = {'username':bitbucket_username}, key_prefix=custom_prefix)
            expire_view_cache('bitbucket_username_watched', kwargs = {'username':bitbucket_username}, key_prefix=custom_prefix)

        category_links = instance.userrepositorylink_set.order_by('repository_category').distinct('repository_category')
        for category_link in category_links:

            expire_view_cache('authed_category_owned', kwargs = {'category':category_link.repository_category.name}, key_prefix=custom_prefix)