import csv

from rest_framework import generics
from rest_framework.authentication import BaseAuthentication
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.views import APIView

from .models import *


from rest_framework.response import Response
from rest_framework import status
from django.http import Http404

from .serializer import OtherCropInfoSerializer, CropInfoSerializer, OtherLandInfoSerializer, LandInfoSerializer, \
    FarmerRegistrationSerializer


class FarmerRegistrationListView(generics.ListCreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = FarmerRegistrationSerializer

    def get_queryset(self):
        return FarmerRegistration.objects.filter(user=self.request.user)

    def create(self, request, *args, **kwargs):
        mutable_data = request.data.copy()  # Create a mutable copy of request data
        mutable_data['user'] = request.user.id  # Assign the user based on the token
        serializer = self.get_serializer(data=mutable_data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class LandInfoListView(generics.ListCreateAPIView):
    serializer_class = LandInfoSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        land_info_id = self.request.query_params.get('land_info_id', None)

        if land_info_id:
            # If land_info_id is provided, filter by user and land_info_id
            return LandInfo.objects.filter(user=user, id=land_info_id)
        else:
            # Otherwise, return all LandInfo objects for the user
            return LandInfo.objects.filter(user=user)

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)

        # Add related OtherLandInfo objects to the serialized data
        for land_info_data in serializer.data:
            other_land_info_queryset = OtherLandInfo.objects.filter(land_info_id=land_info_data['id'])
            other_land_info_serializer = OtherLandInfoSerializer(other_land_info_queryset, many=True)
            land_info_data['other_land_info'] = other_land_info_serializer.data

        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        mutable_data = request.data.copy()
        mutable_data['user'] = request.user.id  # Assign the authenticated user's ID

        serializer = self.get_serializer(data=mutable_data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)



class OtherLandInfoListView(generics.ListCreateAPIView):
    serializer_class = OtherLandInfoSerializer

    def get_queryset(self):
        land_info_id = self.request.query_params.get('land_info_id')
        if land_info_id is not None:
            return OtherLandInfo.objects.filter(land_info_id=land_info_id)
        return OtherLandInfo.objects.all()

    def perform_create(self, serializer):
        land_info_id = self.request.query_params.get('land_info_id')
        try:
            land_info_instance = LandInfo.objects.get(pk=land_info_id)
        except LandInfo.DoesNotExist:
            raise Http404("LandInfo matching query does not exist.")

        serializer.save(land_info_id=land_info_instance)



class CropInfoListView(generics.ListCreateAPIView):
    serializer_class = CropInfoSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        crop_info_id = self.request.query_params.get('crop_info_id', None)

        if crop_info_id:
            # If crop_info_id is provided, filter by user and crop_info_id
            return CropInfo.objects.filter(user=user, id=crop_info_id)
        else:
            # Otherwise, return all CropInfo objects for the user
            return CropInfo.objects.filter(user=user)

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)

        # Add related OtherCropInfo objects to the serialized data
        for crop_info_data in serializer.data:
            other_crop_info_queryset = OtherCropInfo.objects.filter(crop_info_id=crop_info_data['id'])
            other_crop_info_serializer = OtherCropInfoSerializer(other_crop_info_queryset, many=True)
            crop_info_data['other_crop_info'] = other_crop_info_serializer.data

        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        mutable_data = request.data.copy()
        mutable_data['user'] = request.user.id  # Assign the authenticated user's ID

        serializer = self.get_serializer(data=mutable_data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class OtherCropInfoListView(generics.ListCreateAPIView):
    serializer_class = OtherCropInfoSerializer

    def get_queryset(self):
        crop_info_id = self.request.query_params.get('crop_info_id')
        if crop_info_id is not None:
            return OtherCropInfo.objects.filter(crop_info_id=crop_info_id)
        return OtherCropInfo.objects.all()

    def perform_create(self, serializer):
        crop_info_id = self.request.query_params.get('crop_info_id')
        try:
            crop_info_instance = CropInfo.objects.get(pk=crop_info_id)
        except CropInfo.DoesNotExist:
            raise Http404("CropInfo matching query does not exist.")

        serializer.save(crop_info_id=crop_info_instance)

class NoAuthentication(BaseAuthentication):
    def authenticate(self, request):
        return None
class DistrictKrishibhavanAPI(APIView):
    authentication_classes = [NoAuthentication]
    permission_classes = [AllowAny]

    def get(self, request):
        district = request.query_params.get('district')

        # Read data from the CSV file and create the dummy_krishibavans dictionary
        dummy_krishibavans = {}
        with open('registering/csv/krishibhavan1.csv', newline='') as csvfile:
            csv_reader = csv.DictReader(csvfile)
            for row in csv_reader:
                district_name = row['District']
                krishibhavan_name = row['Krishibhavan']
                if district_name not in dummy_krishibavans:
                    dummy_krishibavans[district_name] = []
                dummy_krishibavans[district_name].append(krishibhavan_name)

        if district in dummy_krishibavans:
            krishibavans = dummy_krishibavans[district]
            return Response({'krishibavans': krishibavans}, status=status.HTTP_200_OK)
        else:
            return Response({'error': 'District not found'}, status=status.HTTP_404_NOT_FOUND)







class FieldNameListAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user

        # Get field names from LandInfo
        land_info_field_names = LandInfo.objects.filter(user=user).values_list('field_name', flat=True)

        # Get field names from OtherLandInfo
        other_land_info_field_names = OtherLandInfo.objects.filter(land_info_id__user=user).values_list('field_name', flat=True)

        # Combine both lists
        combined_field_names = list(land_info_field_names) + list(other_land_info_field_names)

        return Response({'field_names': combined_field_names})