# coding: utf-8

from rest_framework.permissions import BasePermission

from procu.api import models


class FileRetrievePermission(BasePermission):
    def has_permission(self, request, view):
        return request.user.has_perms(('api.retrieve_attachment',))

    def has_object_permission(self, request, view, obj):

        perm = False

        # Common permissions

        if not perm and obj.comment_id:
            perm = (
                models.Quote.objects.permitted(request.user)
                .filter(comments=obj.comment_id)
                .exists()
            )

        if not perm and obj.request_id:
            perm = (
                models.Request.objects.permitted(request.user)
                .filter(id=obj.request_id)
                .exists()
            )

        # Staff-only permissions

        if request.user.is_staff:

            if not perm and obj.enquiry_id:
                perm = (
                    models.Enquiry.objects.permitted(request.user)
                    .filter(id=obj.enquiry_id)
                    .exists()
                )

            if not perm and obj.enquiry_comment_id:
                perm = (
                    models.Enquiry.objects.permitted(request.user)
                    .filter(comments=obj.enquiry_comment_id)
                    .exists()
                )

        return perm
