from django.utils import translation
from django.utils.functional import cached_property
from rest_framework import status
from rest_framework.exceptions import PermissionDenied
from rest_framework.response import Response

from intranet.femida.src.actionlog.decorators import action_logged
from intranet.femida.src.api.core.views import BaseView, BaseFormViewMixin, ResponseError
from intranet.femida.src.api.offers.base_views import (
    AttachmentUploadBaseView,
    AttachEdsPhoneBaseView,
    VerifyEdsPhoneBaseView,
)
from intranet.femida.src.core.choices import DRF_THROTTLE_SCOPES
from intranet.femida.src.offers.controllers import PreprofileCtl
from intranet.femida.src.offers.mixins import PreprofileByUidViewMixin
from intranet.femida.src.offers.models import Preprofile

from . import serializers, forms


class NewhireDataMixin:

    @cached_property
    def newhire_data(self):
        data = self.ctl.newhire_data
        if not data:
            raise ResponseError(
                data={'error': [{'code': 'internal_server_error'}]},
                status=status.HTTP_400_BAD_REQUEST,
            )
        return data


class PreprofileCreateView(BaseView):

    model_class = Preprofile
    detail_serializer_class = serializers.PreprofileSerializer
    validator_class = forms.PreprofileForm

    @action_logged('preprofile_create')
    def post(self, request, *args, **kwargs):
        """
        Создает связь препрофайла в Наниматоре
        со ссылкой на внешнюю анкету
        """
        if not self.request.user.has_perm('permissions.can_use_api_for_newhire'):
            raise PermissionDenied
        return self.create(request, *args, **kwargs)

    def perform_create(self, data):
        ctl = PreprofileCtl.get_or_create(data)
        return ctl.instance


class PreprofileAcceptView(PreprofileByUidViewMixin, NewhireDataMixin, BaseFormViewMixin, BaseView):

    model_class = Preprofile
    validator_class = forms.PreprofileAcceptForm
    form_serializer_class = serializers.PreprofileAcceptFormSerializer
    authentication_classes = []
    permission_classes = []
    throttle_scope = DRF_THROTTLE_SCOPES.ext_form_accept

    def get_initial_data(self):
        return self.form_serializer_class(self.newhire_data).data

    def initial(self, request, *args, **kwargs):
        translation.activate(self.get_language())
        return super().initial(request, *args, **kwargs)

    def get_object(self):
        return self.preprofile

    def get_validator_context(self):
        return {
            'preprofile': self.get_object(),
            'newhire_data': self.newhire_data,
        }

    @action_logged('preprofile_accept')
    def post(self, request, *args, **kwargs):
        self.ctl.update_link_counter()
        return self.update(request, *args, **kwargs)

    def perform_update(self, data, instance):
        self.ctl.accept(data)
        return instance


class PreprofileCheckLoginExternalView(PreprofileByUidViewMixin, NewhireDataMixin, BaseView):
    """
    Валидациия логина для препрофайла на внеш.анкете
    """
    authentication_classes = []
    permission_classes = []
    validator_class = forms.PreprofileCheckLoginExternalForm
    throttle_scope = DRF_THROTTLE_SCOPES.ext_form_check_login

    def get_validator_context(self):
        return {
            'preprofile': self.preprofile,
            'newhire_data': self.newhire_data,
        }

    def get(self, request, *args, **kwargs):
        translation.activate(self.get_language())
        validator = self.get_validator_object(request.query_params)
        self.validate(validator)
        return Response(status=status.HTTP_200_OK)


class PreprofileAttachmentUploadView(PreprofileByUidViewMixin, AttachmentUploadBaseView):

    actionlog_name = 'preprofile_attachment_upload'
    controller_class = PreprofileCtl
    throttle_scope = DRF_THROTTLE_SCOPES.ext_form_attachment_upload

    def get_object(self):
        return self.preprofile


class PreprofileAttachEdsPhoneView(PreprofileByUidViewMixin, AttachEdsPhoneBaseView):
    """
    Ручка прикрепления телефона для электронной подписи
    """
    actionlog_name = 'preprofile_attach_eds_phone'
    authentication_classes = []
    permission_classes = []
    model_class = Preprofile
    throttle_classes = []

    @property
    def instance(self):
        return self.preprofile


class PreprofileVerifyEdsPhoneView(PreprofileByUidViewMixin, VerifyEdsPhoneBaseView):
    """
    Ручка для подтверждения номера телефона по коду из смс
    """
    actionlog_name = 'preprofile_verify_eds_phone'
    authentication_classes = []
    permission_classes = []
    model_class = Preprofile

    @property
    def instance(self):
        return self.preprofile
