# coding: utf-8


import logging

from idm.api.exceptions import BadRequest
from idm.api.frontend.base import FrontendApiResource
from idm.api.frontend.forms import RoleRequestPermissionsForm
from idm.api.frontend.requesthelpers import convert_role_request_exceptions
from idm.core.models import Role


log = logging.getLogger(__name__)


class RoleRequestPermissionsResource(FrontendApiResource):
    """Ресурс, проверяющий право на запрос роли
    """

    class Meta(FrontendApiResource.Meta):
        abstract = False
        object_class = None
        resource_name = 'permissions/rolerequest'
        list_allowed_methods = ['post']
        detail_allowed_methods = []

    def post_list(self, request, **kwargs):
        data = self.deserialize(request, request.body)
        requester = self.get_requester(request, data)

        form = RoleRequestPermissionsForm(data)
        if not form.is_valid():
            raise BadRequest(form.errors)

        data = form.cleaned_data

        subject = form.get_subject()
        system = data['system']
        role_node = data['path']
        fields_data = data['fields_data']

        with convert_role_request_exceptions():
            Role.objects.check_role_request(requester, subject, system, role_node, fields_data)

        return self.create_response(request, data=None, status=204)
