# Path: app/services/utils.py
# def json_response(data, success=True):
#     """
#     Creates a HttpResponse for returning json data.
# 
#     @param data: Object
#     @return: HttpResponse
#     """
#     return HttpResponse(json.dumps({
#             'response': data,
#             'success': success
#         }, separators=(',', ':'), indent=4),
#         content_type="application/json", status=200)
# 
# Path: app/achievement/utils.py
# def find_nested_json(obj, keys):
#     """
#     Finds a nested value in an object, given a list of keys.  If
#     any object is an array within the nested object, returns an
#     array of the resulting call.
# 
#     @param obj: json
#     @param keys: list of string
#     @return: list of objects
#     """
#     enqueued = collections.deque([(obj, keys)])
#     results = []
# 
#     while len(enqueued) > 0:
#         obj, keys = enqueued.popleft()
#         keys_queue = collections.deque(keys)
#         # Iterate over the list of keys
#         while len(keys_queue) > 0:
#             key = keys_queue.popleft()
#             # Check if key is in the object
#             if not key in obj:
#                 return None
# 
#             # Key is in the object, if found a list, enqueue
#             # the list, otherwise enqueue the single item
#             obj = obj[key]
#             keys.pop(0)
# 
#             if type(obj) == list:
#                 enqueued.extend((o, keys[:]) for o in obj)
#                 keys_queue.clear()
# 
#             elif len(keys_queue) == 0:
#                 results.append(obj)
# 
#     if len(results) == 0:
#         return None
# 
#     return results
# 
# Path: app/achievement/hooks.py
# def check_for_unlocked_achievements(event, payload, user=None):
#     """
#     Checks if a user has unlocked any achievements, given the event
#     and event payload as input.
# 
#     @param event: Name of the event
#     @param payload: Dictionary of key-value event data
#     @param user: The User/UserProfile model or name of a user
#     @return: listof Achievement
#     """
#     if isinstance(user, basestring):
#         # There's a guarantee that usernames are unique
#         if User.objects.filter(username=user).count() == 1:
#             user = User.objects.get(username=user).profile
#         elif UserProfile.objects.filter(user__username=user).count() == 1:
#             user = UserProfile.objects.get(user__username=user)
#         else:
#             return []
#     elif isinstance(user, User):
#         user = user.profile
# 
#     unlocked_achievements = []
#     if user:
#         achievements = Achievement.objects.exclude(Q(active=False) | Q(pk__in=
#             map(lambda u: u.pk, user.achievements)))
#     else:
#         achievements = Achievement.objects.exclude(active=False)
# 
#     for achievement in achievements:
#         if achievement.unlocked(event, payload):
#             unlocked_achievements.append(achievement.to_json())
#             if user:
#                 unlocked_achievement = UserAchievement(achievement=achievement, user=user)
#                 unlocked_achievement.save()
# 
#     return unlocked_achievements


from app.services.utils import json_response
from app.achievement.utils import find_nested_json
from app.achievement.hooks import check_for_unlocked_achievements
        'member': 'member.login',
        'page_build': 'build.pusher.login',
        'pull_request': {
            'opened': 'pull_request.user.login',
            'default': 'sender.login'
        },
        'push': 'commits.author.username',
        'release_event': 'release.author.login',
        'team_add': 'user.login',
        'watch': 'sender.login'
    }

    def __init__(self, event_type, *args, **kwargs):
        self.payload = kwargs
        # Find the individual aspects of a payload.  These vary depending on
        # the hook that was triggered.
        self.user = None
        key_pattern = EventData.USER_KEY_PATTERNS.get(event_type, None)

        if key_pattern is not None:
            # If a key pattern exists, find the user using that key
            # pattern
            if isinstance(key_pattern, str):
                user = find_nested_json(kwargs, key_pattern.split('.'))
                if isinstance(user, list):
                    self.user = user[0]
                elif user:
                    self.user = user
            else:
                key_pattern = key_pattern.get(kwargs.get('action', ''), key_pattern['default'])

# Path: app/services/utils.py
# def json_response(data, success=True):
#     """
#     Creates a HttpResponse for returning json data.
# 
#     @param data: Object
#     @return: HttpResponse
#     """
#     return HttpResponse(json.dumps({
#             'response': data,
#             'success': success
#         }, separators=(',', ':'), indent=4),
#         content_type="application/json", status=200)
# 
# Path: app/achievement/utils.py
# def find_nested_json(obj, keys):
#     """
#     Finds a nested value in an object, given a list of keys.  If
#     any object is an array within the nested object, returns an
#     array of the resulting call.
# 
#     @param obj: json
#     @param keys: list of string
#     @return: list of objects
#     """
#     enqueued = collections.deque([(obj, keys)])
#     results = []
# 
#     while len(enqueued) > 0:
#         obj, keys = enqueued.popleft()
#         keys_queue = collections.deque(keys)
#         # Iterate over the list of keys
#         while len(keys_queue) > 0:
#             key = keys_queue.popleft()
#             # Check if key is in the object
#             if not key in obj:
#                 return None
# 
#             # Key is in the object, if found a list, enqueue
#             # the list, otherwise enqueue the single item
#             obj = obj[key]
#             keys.pop(0)
# 
#             if type(obj) == list:
#                 enqueued.extend((o, keys[:]) for o in obj)
#                 keys_queue.clear()
# 
#             elif len(keys_queue) == 0:
#                 results.append(obj)
# 
#     if len(results) == 0:
#         return None
# 
#     return results
# 
# Path: app/achievement/hooks.py
# def check_for_unlocked_achievements(event, payload, user=None):
#     """
#     Checks if a user has unlocked any achievements, given the event
#     and event payload as input.
# 
#     @param event: Name of the event
#     @param payload: Dictionary of key-value event data
#     @param user: The User/UserProfile model or name of a user
#     @return: listof Achievement
#     """
#     if isinstance(user, basestring):
#         # There's a guarantee that usernames are unique
#         if User.objects.filter(username=user).count() == 1:
#             user = User.objects.get(username=user).profile
#         elif UserProfile.objects.filter(user__username=user).count() == 1:
#             user = UserProfile.objects.get(user__username=user)
#         else:
#             return []
#     elif isinstance(user, User):
#         user = user.profile
# 
#     unlocked_achievements = []
#     if user:
#         achievements = Achievement.objects.exclude(Q(active=False) | Q(pk__in=
#             map(lambda u: u.pk, user.achievements)))
#     else:
#         achievements = Achievement.objects.exclude(active=False)
# 
#     for achievement in achievements:
#         if achievement.unlocked(event, payload):
#             unlocked_achievements.append(achievement.to_json())
#             if user:
#                 unlocked_achievement = UserAchievement(achievement=achievement, user=user)
#                 unlocked_achievement.save()
# 
#     return unlocked_achievements


# Path: app/services/hooks/github.py
from app.services.utils import json_response
from app.achievement.utils import find_nested_json
from app.achievement.hooks import check_for_unlocked_achievements

        'member': 'member.login',
        'page_build': 'build.pusher.login',
        'pull_request': {
            'opened': 'pull_request.user.login',
            'default': 'sender.login'
        },
        'push': 'commits.author.username',
        'release_event': 'release.author.login',
        'team_add': 'user.login',
        'watch': 'sender.login'
    }

    def __init__(self, event_type, *args, **kwargs):
        self.payload = kwargs
        # Find the individual aspects of a payload.  These vary depending on
        # the hook that was triggered.
        self.user = None
        key_pattern = EventData.USER_KEY_PATTERNS.get(event_type, None)

        if key_pattern is not None:
            # If a key pattern exists, find the user using that key
            # pattern
            if isinstance(key_pattern, str):
                user = find_nested_json(kwargs, key_pattern.split('.'))
                if isinstance(user, list):
                    self.user = user[0]
                elif user:
                    self.user = user
            else:
                key_pattern = key_pattern.get(kwargs.get('action', ''), key_pattern['default'])

                user = find_nested_json(kwargs, key_pattern.split('.'))