import logging

from django.contrib.auth import authenticate, login, logout
from django.utils.translation import gettext_lazy
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

_log = logging.getLogger(__name__)


class LoginView(APIView):
    """Login API with json data."""

    permission_classes = [AllowAny]

    def post(self, request):
        username = request.data['username']
        password = request.data['password']
        user = authenticate(request, username=username, password=password)
        if user is None or not user.is_active:
            _log.info(f'Authenticate error with username[{user}]')
            return Response({'detail': gettext_lazy('Invalid credentials.')}, status=400)
        login(request, user)
        return Response({'status': 'ok'}, status=200)


class LogoutView(APIView):
    """Logout API."""
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        _log.info(f'Logout user [{request.user.username}]')
        logout(request)
        return Response()
