# coding: utf-8

from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from rest_framework.permissions import BasePermission

from procu.api import enums, models
from procu.rest.exceptions import ValidationError


class ListReplaceProductsPermission(BasePermission):
    def has_permission(self, request, view):

        qs = models.Quote.objects.permitted(request.user)

        try:
            quote = qs.values('deadline_at', 'status').get(
                id=view.kwargs['quote_id']
            )

            # Show a human-friendly error when the request expires
            # while the offer form is still opened.
            if request.method == 'PUT' and (
                quote['deadline_at'] <= timezone.now()
                or quote['status'] >= enums.QS.CHECKOUT
            ):
                raise ValidationError(_('ERRORS::REQUEST_EXPIRED'))

            return True

        except models.Quote.DoesNotExist:
            pass

        return False
