"""This module contains the v2 api related-views for the accounts app"""

from django.conf import settings

import waffle
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response

from mtp.apps.accounts.models import MTPUser
from mtp.apps.api.mixins import SoftDestroyModelMixin
from mtp.apps.common.notifications.tasks import send_async

from .serializers import MTPUserSerializer


class UserViewSet(SoftDestroyModelMixin, viewsets.ModelViewSet):
    """Viewset for the ``MTPUser`` model"""

    queryset = MTPUser.objects.non_deleted().prefetch_related('mgroups', 'photo')
    permission_classes = (IsAuthenticated,)
    serializer_class = MTPUserSerializer

    def get_permissions(self):
        """We allow unauthenticated user to create a new account."""

        if self.request.method == 'POST':
            self.permission_classes = (AllowAny,)

        return super().get_permissions()

    @list_route()
    def me(self, request):
        """Retrieve and serialize the authenticated user

        Returns
        -------
        ``rest_framework.response.Response`` instance
            A response containing the serialized user

        """

        serializer = self.get_serializer(request.user)

        return Response(serializer.data)

    def perform_create(self, serializer):
        """Send the welcome mail if applicable

        For the parameters, see ``rest_framework.mixins.CreateModelMixin``"""

        user = serializer.save()

        if settings.INSTANCE_IS_MASTER and waffle.switch_is_active('enable_user_welcome_mail'):
            send_async.delay([user], 'user_welcome')
