import logging

from idm.api.exceptions import BadRequest
from idm.core.models import System
from idm.framework.requester import Requester

from idm.api.v1 import forms

log = logging.getLogger(__name__)


class RequesterMixin:
    def get_requester(self, request, data=None):
        if data is None:
            if request.method in ('GET', 'HEAD'):
                data = request.GET
            elif request.body:
                data = self.deserialize(request, request.body)
            else:
                data = request.GET

        form = forms.RequesterForm(data)

        if not form.is_valid():
            raise BadRequest(form.errors)

        requester = form.cleaned_data['_requester']

        if requester:
            return Requester(
                impersonated=requester,
                impersonator=request.user,
                allowed_systems=list(System.objects.permitted_for(request.user, 'core.can_impersonate')),
            )

        return super(RequesterMixin, self).get_requester(request, data)
