from rest_framework import permissions
from fb.staff.models import Person


class IsOwner(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):
        try:
            staff_user = Person.objects.get(uid=request.yauser.uid)
            return obj.reporter == staff_user
        except Person.DoesNotExist:
            return False


class IsOwnerOrHeadChangesMood(permissions.BasePermission):

    @staticmethod
    def can_see(watcher, person):
        if watcher.is_head_of(person):
            return True
        if watcher.has_read_role(person):
            return True
        return False

    def has_object_permission(self, request, view, obj):
        try:
            staff_user = Person.objects.get(uid=request.yauser.uid)
        except Person.DoesNotExist:
            return False

        if obj.reporter == staff_user:
            return True

        if not any(self.can_see(staff_user, p) for p in obj.persons.all()):
            return False

        if request.method in ['HEAD', 'GET']:
            return True

        if len(request.DATA.keys()) != 1 or 'mood' not in request.DATA:
            return False

        return True


class IsOwnerOrSuggestTo(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        try:
            staff_user = Person.objects.get(uid=request.yauser.uid)
            return (obj.reporter == staff_user) or (staff_user == obj.suggest_to)
        except Person.DoesNotExist:
            return False
