from django.http import Http404
from rest_framework.permissions import AllowAny, IsAuthenticated, DjangoObjectPermissions

class IsAdminOrStaff:
  def has_permission(self, request, view):
    return request.user and (request.user.is_superuser or request.user.is_staff)

  def has_object_permission(self, request, view, obj):
    return self.has_permission(request, view)

class IsClientUser:
  def has_permission(self, request, view):
    return request.user and getattr(request.user, 'client', None)

  def has_object_permission(self, request, view, obj):
    return self.has_permission(request, view)

class CustomObjectPermissions(DjangoObjectPermissions):
  perms_map = {
    'OPTIONS': [],
    'HEAD':    [],
    'GET':     ['%(app_label)s.view_%(model_name)s'],
    'POST':    ['%(app_label)s.add_%(model_name)s'],
    'PUT':     ['%(app_label)s.change_%(model_name)s'],
    'PATCH':   ['%(app_label)s.change_%(model_name)s'],
    'DELETE':  ['%(app_label)s.delete_%(model_name)s'],
  }

  # default implementation raises Http404 instead of returning False for security reasons
  # - by returning 403 we admit existence of the object
  # - but this behavior is harder to debug, since we can't distinguish between real 404 and this
  #   situation, so let's return 403 for now
  def has_object_permission(self, request, view, obj):
    try:
      return super().has_object_permission(request, view, obj)
    except Http404:
      return False

  def has_permission(self, request, view):
    return self.has_object_permission(request, view, None)
