from rest_framework import generics 
from mama_care.models import *
from mama_care.serializers import *
from django_filters import rest_framework as filters 
from django_filters.rest_framework import DjangoFilterBackend 
from rest_framework import authentication 
from rest_framework import exceptions 
from mama_care_api.settings import *
from mama_care_api.settings import languageKey
from django.http import JsonResponse 
from django.core.files import File 
from rest_framework import pagination 
import json

# API Key Authorization
class APIKeyAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        apiKey = request.headers.get("apiKey")
        errorMessage = ""
        isRequestAuthenticated = False
        if apiKey is not None:
            if apiKey == SECRET_KEY:
                isRequestAuthenticated = True
            else:
                errorMessage = "In Valid API Key"
        else:
            errorMessage = "No API Key Found"

        if isRequestAuthenticated:
            return None
        else:
            raise serializers.ValidationError({"error":[errorMessage]})


class LoginAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        phone = request.query_params.get("phone")
        password = request.query_params.get("password")
        errorMessage = ""
        isValid = False
        if phone is not None and password is not None:
            selectedList = Parent.objects.filter(phone=phone).filter(parent_parentdetail__password=password)
            if selectedList.__len__() > 0:
                parent = selectedList[0]
                isExists = ParentDetail.objects.filter(parentId = parent.id).exists()
                if(isExists == True):
                    parentDetail = ParentDetail.objects.get(parentId = parent.id)
                    if parent.phone == phone and parentDetail.password == password:
                        isValid = True
                    else:
                        errorMessage = "phone and password is invalid"
                else:
                    errorMessage = "No Records found"
            else:
                errorMessage = "No Records found"
        else:
            errorMessage = "phone and password is required"

        if isValid:
            return None
        else:
            raise serializers.ValidationError({"error":[errorMessage]})


# Authentication
class DashboardTokenAuthentication(authentication.BaseAuthentication):

    def checkToken(self, token):
        if token is not None:
            if token != "":
                return True
        return False

    def checkAdminAuth(self, token):
        if token == "admin":
            return True
        return False

    def authenticate(self, request):
        isDashboard = request.headers.get("isDashboard")
        token = request.headers.get("token")
        isAuthenticated = False
        errorMessage = ""
        if self.checkToken(token) == True:
            if isDashboard == "1":
                if self.checkAdminAuth(token) == True:
                    isAuthenticated = True
                else:
                    errorMessage = "In Valid Token"
        else:
            errorMessage = "Token is required"

        if isAuthenticated:
            return None
        else:
            raise serializers.ValidationError({"error":[errorMessage]})

class MobileTokenAuthentication(authentication.BaseAuthentication):

    def tryParseInt(self, val):
        try:
            return int(val)
        except (ValueError, TypeError):
            return None

    def checkLanguage(self, languageId):
        if self.tryParseInt(languageId) is not None:
            val = getLanguageRecord(languageId)
            if val == int(languageId):
                return True
        return False

    def checkToken(self, token):
        if token is not None:
            if token != "":
                return True
        return False

    def checkParentAuth(self, token, parentId):
        if self.tryParseInt(parentId) is not None:
            parentTokenList = ParentToken.objects.filter(token=token)
            if parentTokenList.__len__() > 0:
                selected = parentTokenList[0]
                if selected.parentId.id == int(parentId) and selected.token == token:
                    return True
            return False
        return False

    def checkGuestAuth(self, token):
        if token == "guest":
            return True
        return False

    def authenticate(self, request):
        languageId = request.headers.get(languageKey)
        token = request.headers.get("token")
        kwargs = request.parser_context.get("kwargs", {})
        parentIdPK = kwargs.get("pk")
        parentIdFK = request.query_params.get("parentId")

        isAuthenticated = False
        errorMessage = ""

        parentId = None
        if parentIdPK is not None:
            parentId = parentIdPK
        elif parentIdFK is not None:
            parentId = parentIdFK

        if parentId is not None:
            if self.checkToken(token) == True:
                if self.checkParentAuth(token,parentId) == True:
                    isAuthenticated = True
                elif self.checkGuestAuth(token) == True:
                    isAuthenticated = True
                else:
                    errorMessage = "Invalid Token"
            else:
                errorMessage = "Token is required"
        else:
            errorMessage = "Parent Id is required"

        isLanguageValid = self.checkLanguage(languageId)

        if isAuthenticated:
            if isLanguageValid:
                return None
            else:
                errorMessage = "Language is required"
                raise serializers.ValidationError({"error":[errorMessage]})
        else:
            raise serializers.ValidationError({"error":[errorMessage]})

class StandardSetPagination(pagination.PageNumberPagination):
    page_size = 20  # default amount records in current page
    page_size_query_param = "page_size"
    max_page_size = (
        1000  # max number of records in current page by using query param above
    )



# Create your views here.

#Device OS Type

class DeviceOSTypeListMobileView(generics.ListAPIView):
    authentication_classes = [APIKeyAuthentication]
    queryset = DeviceOSType.objects.all()
    serializer_class = DeviceOSTypeSerializer

class DeviceOSTypeListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = DeviceOSType.objects.all()
    serializer_class = DeviceOSTypeSerializer

class DeviceOSTypeDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    lookup_field = "id"
    queryset = DeviceOSType.objects.all()
    serializer_class = DeviceOSTypeSerializer

# Language Views
class LanguageListMobileView(generics.ListAPIView):
    authentication_classes = [APIKeyAuthentication]
    queryset = Language.objects.filter(isEnabled=True)
    serializer_class = LanguageSerializer


class LanguageListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = Language.objects.all()
    serializer_class = LanguageSerializer


class LanguageDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = Language.objects.all()
    lookup_field = "id"
    serializer_class = LanguageSerializer


# Child Type Views


class ChildTypeListMobileView(generics.ListAPIView):
    authentication_classes = [APIKeyAuthentication]
    queryset = ChildType.objects.all()
    serializer_class = ChildTypeSerializer


# Gender Views


class GenderListMobileView(generics.ListAPIView):
    authentication_classes = [APIKeyAuthentication]
    queryset = Gender.objects.all()
    serializer_class = GenderSerializer


# Symptom Type Views
class SymptomTypeListMobileView(generics.ListAPIView):
    authentication_classes = [APIKeyAuthentication]
    queryset = SymptomType.objects.all()
    serializer_class = SymptomTypeSerializer


class SymptomTypeListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = SymptomType.objects.all()
    serializer_class = SymptomTypeSerializer


class SymptomTypeDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = SymptomType.objects.all()
    lookup_field = "id"
    serializer_class = SymptomTypeSerializer


class SymptomTypeLanguageListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = SymptomTypeLanguage.objects.all()
    serializer_class = SymptomTypeLanguageSerializer


class SymptomTypeLanguageDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = SymptomTypeLanguage.objects.all()
    lookup_field = "id"
    serializer_class = SymptomTypeLanguageSerializer


# Kick Tracker Status Views


class KickTrackerStatusListMobileView(generics.ListAPIView):
    authentication_classes = [APIKeyAuthentication]
    queryset = KickTrackerStatus.objects.all()
    serializer_class = KickTrackerStatusSerializer


# BMI Case Type


class BMICaseTypeListMobileView(generics.ListAPIView):
    authentication_classes = [APIKeyAuthentication]
    queryset = BMICaseType.objects.all()
    serializer_class = BMICaseTypeSerializer


class BMICaseTypeListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = BMICaseType.objects.all()
    serializer_class = BMICaseTypeSerializer


class BMICaseTypeDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = BMICaseType.objects.all()
    lookup_field = "id"
    serializer_class = BMICaseTypeSerializer


class BMICaseTypeLanguageListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = BMICaseTypeLanguage.objects.all()
    serializer_class = BMICaseTypeLanguageSerializer


class BMICaseTypeLanguageDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = BMICaseTypeLanguage.objects.all()
    lookup_field = "id"
    serializer_class = BMICaseTypeLanguageSerializer


# BMI Case Type


class BMICaseListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = BMICase.objects.all()
    serializer_class = BMICaseSerializer


class BMICaseDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = BMICase.objects.all()
    lookup_field = "id"
    serializer_class = BMICaseSerializer


class BMICaseLanguageListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = BMICaseLanguage.objects.all()
    serializer_class = BMICaseLanguageSerializer


class BMICaseLanguageDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = BMICaseLanguage.objects.all()
    lookup_field = "id"
    serializer_class = BMICaseLanguageSerializer


# BMI Case Weight Gain


class BMICaseWeightGainListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = BMICaseWeightGain.objects.all()
    serializer_class = BMICaseWeightGainSerializer


class BMICaseWeightGainDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = BMICaseWeightGain.objects.all()
    lookup_field = "id"
    serializer_class = BMICaseWeightGainSerializer

# Calculation Method

class CalculationMethodListMobileView(generics.ListAPIView):
    authentication_classes = [APIKeyAuthentication]
    queryset = CalculationMethod.objects.all()
    serializer_class = CalculationMethodSerializer


class CalculationMethodListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = CalculationMethod.objects.all()
    serializer_class = CalculationMethodSerializer


class CalculationMethodDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    lookup_field = "id"
    queryset = CalculationMethod.objects.all()
    serializer_class = CalculationMethodSerializer

# Calculation Method Language

class CalculationMethodLanguageListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = CalculationMethodLanguage.objects.all()
    serializer_class = CalculationMethodLanguageSerializer


class CalculationMethodLanguageDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    lookup_field = "id"
    queryset = CalculationMethodLanguage.objects.all()
    serializer_class = CalculationMethodLanguageSerializer

#Pregnancy Week

class PregnancyWeekListMobileView(generics.ListAPIView):
    authentication_classes = [APIKeyAuthentication]
    filter_backends = [DjangoFilterBackend]
    queryset = PregnancyWeek.objects.all()
    serializer_class = PregnancyWeekBasicSerializer

class PregnancyWeekDetailMobileView(generics.RetrieveAPIView):
    authentication_classes = [APIKeyAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = PregnancyWeek.objects.all()
    serializer_class = PregnancyWeekDetailSerializer

class PregnancyWeekListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    queryset = PregnancyWeek.objects.all()
    serializer_class = PregnancyWeekDetailSerializer

class PregnancyWeekDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = PregnancyWeek.objects.all()
    serializer_class = PregnancyWeekDetailSerializer

class PregnancyWeekLanguageListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    queryset = PregnancyWeekLanguage.objects.all()
    serializer_class = PregnancyWeekLanguageSerializer

class PregnancyWeekLanguageDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = PregnancyWeekLanguage.objects.all()
    serializer_class = PregnancyWeekLanguageSerializer

#Pregnancy Symptom

class PregnancySymptomListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    queryset = PregnancySymptom.objects.all()
    serializer_class = PregnancySymptomSerializer

class PregnancySymptomDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = PregnancySymptom.objects.all()
    serializer_class = PregnancySymptomSerializer

class PregnancySymptomLanguageListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    queryset = PregnancySymptomLanguage.objects.all()
    serializer_class = PregnancySymptomLanguageSerializer

class PregnancySymptomLanguageDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = PregnancySymptomLanguage.objects.all()
    serializer_class = PregnancySymptomLanguageSerializer

# Pregnancy CheckList

class PregnancyCheckListListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    queryset = PregnancyCheckList.objects.all()
    serializer_class = PregnancyCheckListSerializer

class PregnancyCheckListDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = PregnancyCheckList.objects.all()
    serializer_class = PregnancyCheckListSerializer

class PregnancyCheckListLanguageListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    queryset = PregnancyCheckListLanguage.objects.all()
    serializer_class = PregnancyCheckListLanguageSerializer

class PregnancyCheckListLanguageDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = PregnancyCheckListLanguage.objects.all()
    serializer_class = PregnancyCheckListLanguageSerializer

# Pregnancy Nutrition

class PregnancyNutritionListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    queryset = PregnancyNutrition.objects.all()
    serializer_class = PregnancyNutritionSerializer

class PregnancyNutritionDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = PregnancyNutrition.objects.all()
    serializer_class = PregnancyNutritionSerializer

class PregnancyNutritionLanguageListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    queryset = PregnancyNutritionLanguage.objects.all()
    serializer_class = PregnancyNutritionLanguageSerializer

class PregnancyNutritionLanguageDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = PregnancyNutritionLanguage.objects.all()
    serializer_class = PregnancyNutritionLanguageSerializer

# Pregnancy Baby Size

class PregnancyBabySizeListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    queryset = PregnancyBabySize.objects.all()
    serializer_class = PregnancyBabySizeDetailSerializer

class PregnancyBabySizeDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = PregnancyBabySize.objects.all()
    serializer_class = PregnancyBabySizeDetailSerializer

class PregnancyBabySizeLanguageListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    queryset = PregnancyBabySizeLanguage.objects.all()
    serializer_class = PregnancyBabySizeLanguageSerializer

class PregnancyBabySizeLanguageDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = PregnancyBabySizeLanguage.objects.all()
    serializer_class = PregnancyBabySizeLanguageSerializer

# Monthly Tips

class MonthlyTipListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    queryset = MonthlyTip.objects.all()
    serializer_class = MonthlyTipSerializer

class MonthlyTipDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = MonthlyTip.objects.all()
    serializer_class = MonthlyTipSerializer

class MonthlyTipLanguageListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    queryset = MonthlyTipLanguage.objects.all()
    serializer_class = MonthlyTipLanguageSerializer

class MonthlyTipLanguageDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = MonthlyTipLanguage.objects.all()
    serializer_class = MonthlyTipLanguageSerializer

# Tip

class TipListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    queryset = Tip.objects.all()
    serializer_class = TipSerializer

class TipDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = Tip.objects.all()
    serializer_class = TipSerializer

class TipLanguageListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    queryset = TipLanguage.objects.all()
    serializer_class = TipLanguageSerializer

class TipLanguageDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = TipLanguage.objects.all()
    serializer_class = TipLanguageSerializer

# Parent Mobile Views
class SignInFilter(filters.FilterSet):
    password = filters.CharFilter(field_name="parent_parentdetail__password", lookup_expr="exact")
    phone = filters.CharFilter(field_name="phone", lookup_expr="exact")
    class Meta:
        model = Parent
        fields = [
            "phone",
            "password"
        ]


class ParentSignInMobileView(generics.ListAPIView):
    authentication_classes = [APIKeyAuthentication,LoginAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_class = SignInFilter
    queryset = Parent.objects.all()
    serializer_class = ParentSerializer

class ParentForgetOrChangePasswordMobileView(generics.GenericAPIView):
    authentication_classes = [APIKeyAuthentication]
    serializer_class = ForgetOrChangePasswordSerializer
    queryset = []

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        result = serializer.save()
        return result

class ParentSignUpMobileView(generics.CreateAPIView):
    authentication_classes = [APIKeyAuthentication]
    serializer_class = ParentSerializer

class ParentDetailSignUpMobileView(generics.CreateAPIView):
    authentication_classes = [APIKeyAuthentication,MobileTokenAuthentication]
    serializer_class = ParentDetailSerializer

class ParentDataMobileView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication]
    queryset = Parent.objects.all()
    serializer_class = ParentSerializer


# Parent Dashboard Views


class ParentListDashboardView(generics.ListAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = Parent.objects.all()
    serializer_class = ParentSerializer


class ParentDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    queryset = Parent.objects.all()
    serializer_class = ParentSerializer


# Child


class ChildListMobileView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentId","childTypeId","genderId"]
    queryset = Child.objects.all()
    serializer_class = ChildSerializer


class ChildDetailMobileView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = Child.objects.all()
    serializer_class = ChildSerializer

# Set App for Child
class SetAppForChild(generics.GenericAPIView):
    authentication_classes = [APIKeyAuthentication,MobileTokenAuthentication]
    queryset = []
    def post(self, request, *args, **kwargs):
        
        parentIdRequest = request.query_params.get("parentId",None)
        
        if parentIdRequest == None:
            raise serializers.ValidationError({"error":"Parent Id is required"})
        
        jsonData = request.data
        if "parentId" not in jsonData:
            raise serializers.ValidationError({"error":"Parent Id is required"})
        
        parentIdData = jsonData["parentId"]
        if int(parentIdRequest) != parentIdData:
            raise serializers.ValidationError({"error":"Parent Id is invalid"})
        
        isExists = Parent.objects.filter(id=parentIdData).exists()

        if isExists == False:
            raise serializers.ValidationError({"error":"Parent Id is invalid"})
        
        if "childId" not in jsonData:
            raise serializers.ValidationError({"error":"Child Id is required"})
        
        childId = jsonData["childId"]
        isExists = Child.objects.filter(id=childId).exists()

        if isExists == False:
            raise serializers.ValidationError({"error":"Child Id is invalid"})
        
        errorMessage = ""
        recordCount = 0
        isSuccess = False
        childCount = Child.objects.filter(parentId = parentIdData).count()
        if childCount > 1:
            selected = Child.objects.get(id=childId)
            if selected.isSelected == False:
                selected.isSelected = True
                selected.save()
                recordCount = Child.objects.exclude(id=childId).update(isSelected = False)
                if recordCount > 0:
                    isSuccess = True
                else:
                    errorMessage = "Nothing Updated"
            else:
                errorMessage = "Already Selected"
        elif childCount <= 1:
            selected = Child.objects.get(id=childId)
            if selected.isSelected == False:
                if selected.isSelected == False:
                    selected.isSelected = True
                    selected.save()
                    isSuccess = True
            else:
                errorMessage = "Already Selected"

        if isSuccess == False:
            raise serializers.ValidationError({"error":[errorMessage]})

        return JsonResponse({"isSuccess": isSuccess}, safe=False)
            

# Emergency Contact


class EmergencyContactListMobileView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentId"]
    queryset = EmergencyContact.objects.all()
    serializer_class = EmergencyContactSerializer


class EmergencyContactDetailMobileView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    lookup_field = "id"
    queryset = EmergencyContact.objects.all()
    serializer_class = EmergencyContactSerializer



# Parent Profile 


class ParentProfileListMobileView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["childId"]
    queryset = ParentProfile.objects.all()
    serializer_class = ParentProfileSerializer


class ParentProfileDetailMobileView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["childId"]
    lookup_field = "childId"
    queryset = ParentProfile.objects.all()
    serializer_class = ParentProfileSerializer


class ParentFilter(filters.FilterSet):

    def getSymptomRowFilters(self, filterColumns):
        filterColumns["symptomTypeId"] = filters.NumberFilter(
            field_name="symptomTypeId", lookup_expr="exact"
        )
        filterColumns["symptomGroupId"] = filters.NumberFilter(
            field_name="symptomGroupId", lookup_expr="exact"
        )
        return filterColumns

    def getKickTrackerGroupFilters(self, filterColumns):
        filterColumns["date"] = filters.DateFilter(
            field_name="date__date", lookup_expr="exact"
        )
        return filterColumns

    def getKickTrackerRowFilters(self, filterColumns):
        filterColumns["kickTrackerGroupId"] = filters.NumberFilter(
            field_name="kickTrackerGroupId", lookup_expr="exact"
        )
        return filterColumns
    
    def getUserDeviceFilters(self, filterColumns):
        filterColumns["token"] = filters.CharFilter(
            field_name="token", lookup_expr="exact"
        )
        return filterColumns
    
    def getTodoFilters(self,filterColumns):
        filterColumns["date"] = filters.DateFilter(
            field_name="date", lookup_expr="exact"
        )
        return filterColumns

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        apiPath = self.request.path.strip("/")
        apiPath = apiPath.split("_mobile")
        apiPath = apiPath[0]

        # Define filters in __init__
        self.filters = {
            "parentId": filters.NumberFilter(
                field_name="parentProfileId__childId__parentId", lookup_expr="exact"
            ),
            "parentProfileId": filters.NumberFilter(
                field_name="parentProfileId", lookup_expr="exact"
            ),
        }

        if apiPath == "symptom_row":
            self.filters = {
                "parentId": filters.NumberFilter(
                    field_name="symptomGroupId__parentProfileId__childId__parentId",
                    lookup_expr="exact",
                ),
            }
            self.filters = self.getSymptomRowFilters(self.filters)
        elif apiPath == "kick_tracker_group":
            self.filters = self.getKickTrackerGroupFilters(self.filters)
        elif apiPath == "kick_tracker_row":
            self.filters = {
                "parentId": filters.NumberFilter(
                    field_name="kickTrackerGroupId__parentProfileId__childId__parentId",
                    lookup_expr="exact",
                ),
            }
            self.filters = self.getKickTrackerRowFilters(self.filters)
        elif apiPath == "user_device":
            self.filters = self.getUserDeviceFilters(self.filters)
        elif apiPath == "todo":
            self.filters = self.getTodoFilters(self.filters)


# Tools

# Symptom Group


class SymptomGroupListMobileView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    pagination_class = StandardSetPagination
    queryset = SymptomGroup.objects.order_by("-date")
    serializer_class = SymptomGroupSerializer


class SymptomGroupDetailMobileView(generics.DestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    lookup_field = "id"
    queryset = SymptomGroup.objects.all()
    serializer_class = SymptomGroupSerializer


# Symptom Row


class SymptomRowListMobileView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["symptomGroupId","symptomTypeId"]
    #filterset_class = ParentFilter
    queryset = SymptomRow.objects.all()
    serializer_class = SymptomRowSerializer


class SymptomRowDetailMobileView(generics.DestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["symptomGroupId","symptomTypeId"]
    #filterset_class = ParentFilter
    lookup_field = "id"
    queryset = SymptomRow.objects.all()
    serializer_class = SymptomRowSerializer


# Kick Tracker Group


class KickTrackerGroupListMobileView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    pagination_class = StandardSetPagination
    queryset = KickTrackerGroup.objects.order_by("-date")
    serializer_class = KickTrackerGroupSerializer


class KickTrackerGroupDetailMobileView(generics.DestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    lookup_field = "id"
    queryset = KickTrackerGroup.objects.all()
    serializer_class = KickTrackerGroupSerializer


# Kick Tracker Row


class KickTrackerRowListMobileView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["kickTrackerGroupId"]
    #filterset_class = ParentFilter
    pagination_class = StandardSetPagination
    queryset = KickTrackerRow.objects.order_by("-date")
    serializer_class = KickTrackerRowSerializer


class KickTrackerRowDetailMobileView(generics.DestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["kickTrackerGroupId"]
    #filterset_class = ParentFilter
    lookup_field = "id"
    queryset = KickTrackerRow.objects.all()
    serializer_class = KickTrackerRowSerializer

# Weight Gain

class WeightGainListMobileView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    pagination_class = StandardSetPagination
    queryset = WeightGain.objects.order_by("-createdDate")
    serializer_class = WeightGainSerializer


class WeightGainDetailMobileView(generics.DestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    lookup_field = "id"
    queryset = WeightGain.objects.all()
    serializer_class = WeightGainSerializer


# Ovluation Calculator

class OvulationListMobileView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    pagination_class = StandardSetPagination
    queryset = Ovulation.objects.order_by('-id')
    serializer_class = OvulationSerializer
    

class OvulationDetailMobileView(generics.DestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    lookup_field = "id"
    queryset = Ovulation.objects.order_by('-id')
    serializer_class = OvulationSerializer


class OvulationListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    pagination_class = StandardSetPagination
    queryset = Ovulation.objects.order_by('-id')
    serializer_class = OvulationSerializer

class OvulationDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    lookup_field = "id"
    queryset = Ovulation.objects.order_by('-id')
    serializer_class = OvulationSerializer

#Due Date Calculator

class DueDateCalculatorListMobileView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    pagination_class = StandardSetPagination
    queryset = DueDateCalculator.objects.all()
    serializer_class = DueDateCalculatorSerializer

class DueDateCalculatorDetailMobileView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    lookup_field = "id"
    queryset = DueDateCalculator.objects.all()
    serializer_class = DueDateCalculatorSerializer

class DueDateCalculatorListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    pagination_class = StandardSetPagination
    queryset = DueDateCalculator.objects.all()
    serializer_class = DueDateCalculatorSerializer

class DueDateCalculatorDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    lookup_field = "id"
    queryset = DueDateCalculator.objects.all()
    serializer_class = DueDateCalculatorSerializer

#Notes

class NotesListMobileView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    pagination_class = StandardSetPagination
    queryset = Notes.objects.all().order_by('-id')
    serializer_class = NotesSerializer

class NotesDetailMobileView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    lookup_field = "id"
    queryset = Notes.objects.all()
    serializer_class = NotesSerializer

class NotesListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #pagination_class = StandardSetPagination
    queryset = Notes.objects.all()
    serializer_class = NotesSerializer

class NotesDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    lookup_field = "id"
    queryset = Notes.objects.all()
    serializer_class = NotesSerializer

# Appointments
class AppointmentListMobileView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    pagination_class = StandardSetPagination
    queryset = Appointment.objects.all().order_by('dateTime').order_by('isDone')
    serializer_class = AppointmentSerializer

class AppointmentDetailMobileView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    lookup_field = "id"
    queryset = Appointment.objects.all()
    serializer_class = AppointmentSerializer

class AppointmentListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    pagination_class = StandardSetPagination
    queryset = Appointment.objects.all().order_by('dateTime').order_by('isDone')
    serializer_class = AppointmentSerializer

class AppointmentDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    lookup_field = "id"
    queryset = Appointment.objects.all()
    serializer_class = AppointmentSerializer


#Calender

# Todo
class TodoListMobileView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    pagination_class = StandardSetPagination
    queryset = Todo.objects.all().order_by('dateTime').order_by('isDone')
    serializer_class = TodoSerializer

class TodoDetailMobileView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, MobileTokenAuthentication, ]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    #filterset_class = ParentFilter
    lookup_field = "id"
    queryset = Todo.objects.all()
    serializer_class = TodoSerializer

class TodoListDashboardView(generics.ListCreateAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    pagination_class = StandardSetPagination
    queryset = Todo.objects.all().order_by('dateTime').order_by('isDone')
    serializer_class = TodoSerializer

class TodoDetailDashboardView(generics.RetrieveUpdateDestroyAPIView):
    authentication_classes = [APIKeyAuthentication, DashboardTokenAuthentication]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["parentProfileId"]
    lookup_field = "id"
    queryset = Todo.objects.all()
    serializer_class = TodoSerializer
