import logging

from django.contrib.auth import get_user_model
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,
    InstanceFormViewMixin,
    WorkflowViewMixin,
)
from intranet.femida.src.communications.choices import MESSAGE_TYPES
from intranet.femida.src.communications.models import Reminder
from intranet.femida.src.communications.workflow import (
    NoteWorkflow,
    ReminderWorkflow,
    InternalMessageWorkflow,
)

from . import serializers, forms

logger = logging.getLogger(__name__)


User = get_user_model()


class ReminderCreateView(BaseFormViewMixin, BaseView):

    validator_class = forms.ReminderCreateForm
    detail_serializer_class = serializers.ReminderCreateSerializer

    _workflow_map = {
        MESSAGE_TYPES.note: NoteWorkflow,
        MESSAGE_TYPES.internal: InternalMessageWorkflow,
    }

    @action_logged('reminder_create')
    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def _get_workflow(self, message):
        if message.type not in self._workflow_map:
            raise PermissionDenied('workflow_error')
        workflow_class = self._workflow_map[message.type]
        return workflow_class(instance=message, user=self.request.user)

    def perform_create(self, data):
        workflow = self._get_workflow(data['message'])
        return workflow.perform_action(action_name='reminder_create', **data)


class ReminderDetailView(WorkflowViewMixin, InstanceFormViewMixin, BaseView):

    model_class = Reminder
    validator_class = forms.ReminderUpdateForm
    form_serializer_class = serializers.ReminderSerializer
    detail_serializer_class = serializers.ReminderSerializer
    workflow_class = ReminderWorkflow

    @action_logged('reminder_update')
    def put(self, request, *args, **kwargs):
        return self.perform_action('update')

    @action_logged('reminder_delete')
    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        data = serializers.NoteForReminderSerializer(
            instance=instance.message,
            context={'user': self.request.user},
        ).data
        return Response(data, status=status.HTTP_200_OK)

    def perform_destroy(self, instance):
        workflow = self.workflow_class(instance=instance, user=self.request.user)
        action = workflow.get_action('delete')
        if not action.is_available():
            raise PermissionDenied('workflow_error')
        return action.perform()
