from django.views.decorators.csrf import csrf_exempt
from rest_framework import permissions, status, viewsets
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth import authenticate
from django.shortcuts import render
from . import models, serializers
from .services import get_car_data, get_from_cardatabase
from rest_framework.authtoken.models import Token
# from inventory.models import CustomUser
from django.utils.decorators import method_decorator


class LoginView(APIView):
    permission_classes = [permissions.AllowAny,]

    def post(self, request, *args, **kwargs):
        username = request.data.get('username')
        password = request.data.get('password')

        if username is None or password is None:
            return Response({'error': 'Please provide both username and password.'}, status=status.HTTP_400_BAD_REQUEST)

        user = authenticate(username=username, password=password)

        if not user:
            return Response({'error': 'Invalid credentials.'}, status=status.HTTP_401_UNAUTHORIZED)

        token, created = Token.objects.get_or_create(user=user)
        return Response({'token': token.key, 'user_id': user.id, 'username': user.username}, status=status.HTTP_200_OK)


class CarVINViewSet(APIView):
    queryset = models.CarVIN.objects.all().order_by('-created')
    serializer_class = serializers.CarVINSerializer

    def get(self, request):
        vin = models.CarVIN.objects.all()
        serializer = serializers.CarVINSerializer(vin, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = serializers.CarVINSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            for key, value in serializer.validated_data.items():
                print(key, value)
                get_car_data(value)
                # get_from_cardatabase(value)
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


