from django.shortcuts import render
from mama_care.models import *
from mama_care.serializers import *
from rest_framework import generics
from mama_care.views import *
from PIL import Image
from django.core.files.base import ContentFile
import io
# Create your views here.

class ResizeImage():

    def resizeImage(self,filePath):
        djangoFile = None

        if os.path.exists(filePath):
            f = open(filePath, "rb")
            djangoFile = File(f)
        if djangoFile is not None:
            # Open image from Django file
            img = Image.open(djangoFile)

            # Resize to 128×128 (you can also use LANCZOS for better quality)
            img = img.resize((100, 100), Image.LANCZOS)

            # Save to in-memory buffer
            buffer = io.BytesIO()
            img.save(buffer, format="PNG")   # or JPEG, WEBP, etc.
            buffer.seek(0)

            # Create a Django ContentFile
            resized_file = ContentFile(buffer.read(), name=djangoFile.name)
            return resized_file
        
        return None

class MonthLyTipData():
    def saveMonthLyTip(self,current):
        monthlyTip = {
            "monthNumber":current["month"],
            "createdDate":datetime.now(),
            "updatedDate":datetime.now()
        }
        monthlyTipSer = MonthlyTipSerializer(data = monthlyTip)
        if monthlyTipSer.is_valid():
            monthlyTipSer.save()

            if "id" in monthlyTipSer.data:
                self.saveMonthlyTipLanguage(current,monthlyTipSer.data["id"],"en",1)
                self.saveMonthlyTipLanguage(current,monthlyTipSer.data["id"],"ar",2)
                self.saveTip(current,monthlyTipSer.data["id"],"en",1)
                self.saveTip(current,monthlyTipSer.data["id"],"ar",2)
    
    def saveMonthlyTipLanguage(self,current,monthlyTipId,lang,langId):
        monthlyTipLanguage = {
            "title":current["title_"+lang],
            "description":current["text_"+lang],
            "inspiration":current["inspiration_"+lang],
            "createdDate":datetime.now(),
            "updatedDate":datetime.now(),
            "monthlyTipId":monthlyTipId,
            languageKey:langId,
        }
        monthlyTipLanguageSer = MonthlyTipLanguageSerializer(data = monthlyTipLanguage)
        if monthlyTipLanguageSer.is_valid():
            monthlyTipLanguageSer.save()

            if "id" in monthlyTipLanguageSer.data:
                return True
        
        return False

    def saveTip(self,current,monthlyTipId,lang,langId):
        if "tips_"+lang in current:
            for selected in current["tips_"+lang]:
                tip = {
                    "createdDate":datetime.now(),
                    "updatedDate":datetime.now(),
                    "monthlyTipId":monthlyTipId
                }
                tipSer = TipSerializer(data = tip)
                if tipSer.is_valid():
                    tipSer.save()
                    if "id" in tipSer.data:
                        self.saveTipLanguage(selected,tipSer.data["id"],langId)
    
    def saveTipLanguage(self,description,tipId,langId):
        tipLanguage = {
            "description":description,
            "createdDate":datetime.now(),
            "updatedDate":datetime.now(),
            "tipId":tipId,
            languageKey:langId
        }
        tipLanguageSer = TipLanguageSerializer(data = tipLanguage)
        if tipLanguageSer.is_valid():
            tipLanguageSer.save()
            if "id" in tipLanguageSer.data:
                return True
        return False

    def readData(self):
        with open(MEDIA_ROOT+"/add_data_json/monthly_tips.json", "r",encoding='utf-8') as file:
            jsonData = json.load(file)
            for monthTips in jsonData:
                self.saveMonthLyTip(monthTips)

class MonthlyTipDataInitial(generics.GenericAPIView):
    authentication_classes = [APIKeyAuthentication]
    queryset = []
    def post(self, request, *args, **kwargs):
        data = MonthLyTipData()
        data.readData()
        return JsonResponse({"isSuccess": True, "error": ""}, safe=False)    

class PregnancyData():

    def saveWeek(self,current):
        filePath = MEDIA_ROOT+"/"+current["image"]
        resizedFile = None
        resizeImage = ResizeImage()
        resizedFile = resizeImage.resizeImage(filePath)

        week = {
            "id":current["week"],
            "keyName":"week_"+str(current["week"]),
            "weekNumber":current["week"],
            "trimester":current["trimester"],
            "image":resizedFile,
            "createdDate":datetime.now(),
            "updatedDate":datetime.now()
        }
        selectedSer =  PregnancyWeekDetailSerializer(data = week)
        if selectedSer.is_valid():
            selectedSer.save()
        
        if "id" in selectedSer.data:
            if selectedSer.data["id"] > 0:
                val1 = self.saveWeekLanguage(current["fetal_development"], selectedSer.data["id"],"en",1)
                val2 = self.saveWeekLanguage(current["fetal_development"], selectedSer.data["id"],"ar",2)
                val3 = self.saveSymptomList(current["symptoms"],selectedSer.data["id"])
                val4 = self.saveCheckList(current["checklist"],selectedSer.data["id"])
                val5 = self.saveNutritionList(current["nutrition"],selectedSer.data["id"])
                val6 = self.saveBabySize(current["baby_size"],selectedSer.data["id"],MEDIA_ROOT+"/add_baby_size/"+"week_"+str(current["week"])+".png")
                if val1 and val2 and val3 and val4 and val5 and val6:
                    return True

        return False

    def saveWeekLanguage(self,current,weekId,langKey,langId):
        isCheck = False
        countError = 0

        weekLanguage = {
            "fetalDevelopment":current[langKey],
            "createdDate":datetime.now(),
            "updatedDate":datetime.now(),
            "pregnancyWeekId":weekId,
            languageKey:langId
        }
        selectedSer = PregnancyWeekLanguageSerializer(data = weekLanguage)
        if selectedSer.is_valid():
            selectedSer.save()
            if "id" in selectedSer.data:
                if selectedSer.data["id"] < 0:
                    countError = countError + 1
        if countError == 0:
            isCheck = True
        return isCheck

    #Symptom
    def saveSymptomList(self,current,weekId):
        enList = current["en"]
        arList = current["ar"]
        if enList.__len__() == arList.__len__():
            for i in range(0,enList.__len__(),1):
                self.saveSymptom(enList[i],arList[i],weekId)

    def saveSymptom(self,descriptionEN,descriptionAR,weekId):
        symptom = {
            "pregnancyWeekId":weekId,
            "createdDate":datetime.now(),
            "updatedDate":datetime.now(),
        }
        selectedSer = PregnancySymptomSerializer(data = symptom)
        if selectedSer.is_valid():
            selectedSer.save()
            if "id" in selectedSer.data:
                val1 = self.saveSymptomLanguage(descriptionEN,selectedSer.data["id"],1)
                val2 = self.saveSymptomLanguage(descriptionAR,selectedSer.data["id"],2)
                if val1 == True and val2 == True:
                    return True
        return False
    
    def saveSymptomLanguage(self,description,symptomId,langId):
        isCheck = False
        countError = 0
        symptomLanguage = {
                "description":description,
                "createdDate":datetime.now(),
                "updatedDate":datetime.now(),
                "pregnancySymptomId":symptomId,
                "languageId":langId
            }
        selectedSer = PregnancySymptomLanguageSerializer(data = symptomLanguage)
        if selectedSer.is_valid():
            selectedSer.save()
            if selectedSer.data["id"] < 0:
                countError = countError + 1
            
        if countError == 0:
                isCheck = True
            
        return isCheck
    
    #CheckList
    def saveCheckList(self,current,weekId):
        enList = current["en"]
        arList = current["ar"]
        if enList.__len__() == arList.__len__():
            for i in range(0,enList.__len__(),1):
                self.saveCheckItem(enList[i],arList[i],weekId)

    def saveCheckItem(self,descriptionEN,descriptionAR,weekId):
        checklist = {
            "pregnancyWeekId":weekId,
            "createdDate":datetime.now(),
            "updatedDate":datetime.now(),
        }
        selectedSer = PregnancyCheckListSerializer(data = checklist)
        if selectedSer.is_valid():
            selectedSer.save()
            if "id" in selectedSer.data:
                val1 = self.saveCheckItemLanguage(descriptionEN,selectedSer.data["id"],1)
                val2 = self.saveCheckItemLanguage(descriptionAR,selectedSer.data["id"],2)
                if val1 == True and val2 == True:
                    return True
        return False
    
    def saveCheckItemLanguage(self,current,symptomId,langId):
        isCheck = False
        countError = 0
        checkListLanguage = {
                "description":current,
                "createdDate":datetime.now(),
                "updatedDate":datetime.now(),
                "pregnancyCheckListId":symptomId,
                "languageId":langId
        }
        selectedSer = PregnancyCheckListLanguageSerializer(data = checkListLanguage)
        if selectedSer.is_valid():
            selectedSer.save()
            if selectedSer.data["id"] < 0:
                countError = countError + 1
            
        if countError == 0:
                isCheck = True
            
        return isCheck
    
    #Nutrition
    def saveNutritionList(self,current,weekId):
        enList = current["en"]
        arList = current["ar"]
        if enList.__len__() == arList.__len__():
            for i in range(0,enList.__len__(),1):
                self.saveNutrition(enList[i],arList[i],weekId)

    def saveNutrition(self,descriptionEN,descriptionAR,weekId):
        nutrition = {
            "pregnancyWeekId":weekId,
            "createdDate":datetime.now(),
            "updatedDate":datetime.now(),
        }
        selectedSer = PregnancyNutritionSerializer(data = nutrition)
        if selectedSer.is_valid():
            selectedSer.save()
            if "id" in selectedSer.data:
                val1 = self.saveNutritionLanguage(descriptionEN,selectedSer.data["id"],1)
                val2 = self.saveNutritionLanguage(descriptionAR,selectedSer.data["id"],2)
                if val1 == True and val2 == True:
                    return True
        return False
    
    def saveNutritionLanguage(self,current,symptomId,langId):
        isCheck = False
        countError = 0
        
        nutritionLanguage = {
                "description":current,
                "createdDate":datetime.now(),
                "updatedDate":datetime.now(),
                "pregnancyNutritionId":symptomId,
                "languageId":langId
            }
        selectedSer = PregnancyNutritionLanguageSerializer(data = nutritionLanguage)
        if selectedSer.is_valid():
            selectedSer.save()
            if selectedSer.data["id"] < 0:
                countError = countError + 1
        
        if countError == 0:
            isCheck = True    
        
        return isCheck

    #BabySize
    def saveBabySize(self,current,weekId,imagePath):
        filePath = imagePath
        djangoFile = None

        resizedFile = None
        resizeImage = ResizeImage()

        if os.path.exists(filePath):
            resizedFile = resizeImage.resizeImage(filePath)
        else:
            filePath = MEDIA_ROOT+"/add_baby_size/"+"week_2.png"
            resizedFile = resizeImage.resizeImage(filePath)

        babySize = {
            "keyName":"week_"+str(weekId),
            "pregnancyWeekId":weekId,
            "image": resizedFile,
            "createdDate":datetime.now(),
            "updatedDate":datetime.now(),
        }
        selectedSer = PregnancyBabySizeDetailSerializer(data = babySize)
        if selectedSer.is_valid():
            selectedSer.save()
            if "id" in selectedSer.data:
                val1 = self.saveBabySizeLanguage(current,selectedSer.data["id"],"en",1)
                val2 = self.saveBabySizeLanguage(current,selectedSer.data["id"],"ar",2)
                if val1 == True and val2 == True:
                    return True
        return False

    def saveBabySizeLanguage(self,current,babySizeId,langKey,langId):
        isCheck = False
        countError = 0

        weekLanguage = {
            "description":current[langKey],
            "createdDate":datetime.now(),
            "updatedDate":datetime.now(),
            "pregnancyBabySizeId":babySizeId,
            languageKey:langId
        }
        selectedSer = PregnancyBabySizeLanguageSerializer(data = weekLanguage)
        if selectedSer.is_valid():
            selectedSer.save()
            if "id" in selectedSer.data:
                if selectedSer.data["id"] < 0:
                    countError = countError + 1
        
        if countError == 0:
            isCheck = True
        return isCheck

    def readData(self):
        with open(MEDIA_ROOT+"/add_data_json/pregnancy_weeks_v3.json", "r",encoding='utf-8') as file:
            jsonData = json.load(file)
            if "weeks" in jsonData:
                for week in jsonData["weeks"]:
                    self.saveWeek(week)

class PregnancyDataInitial(generics.GenericAPIView):
    authentication_classes = [APIKeyAuthentication]
    queryset = []
    def post(self, request, *args, **kwargs):
        data = PregnancyData()
        data.readData()
        return JsonResponse({"isSuccess": True, "error": ""}, safe=False)

# Setup
class SetupInitial(generics.GenericAPIView):
    authentication_classes = [APIKeyAuthentication]
    queryset = []

    def createTokenType(
        self,
        keyName,
        tokenTypeLen,
    ):
        return {
            "keyName": keyName,
            "tokenTypeLen": tokenTypeLen,
            "createdDate": datetime.now(),
            "updatedDate": datetime.now(),
        }

    def addTokenTypeList(self):
        countError = 0

        dataList = [
            self.createTokenType("admin", 110),
            self.createTokenType("parent", 55),
            self.createTokenType("guest", 27),
        ]

        for i in dataList:
            tokenTypeSerializer = TokenTypeSerializer(data=i)
            if tokenTypeSerializer.is_valid():
                tokenTypeSerializer.save()
            else:
                countError = countError + 1

        if countError == 0:
            return True

        return False

    def createLanguage(self, name, countryCode, isEnabled, languageCode):
        return {
            "name": name,
            "countryCode": countryCode,
            "isEnabled": isEnabled,
            "languageCode": languageCode,
            "createdDate": datetime.now(),
            "updatedDate": datetime.now(),
        }

    def addLanguageList(self):
        countError = 0

        dataList = [
            self.createLanguage("English", "US", True, "en"),
            self.createLanguage("Arabic", "SA", True, "ar"),
        ]

        for i in dataList:
            languageSerializer = LanguageSerializer(data=i)
            if languageSerializer.is_valid():
                languageSerializer.save()
            else:
                countError = countError + 1

        if countError == 0:
            return True

        return False

    def createChildType(self, keyName, enName, arName):
        return {
            "keyName": keyName,
            "languageList": [
                {"name": enName, "languageId": 1},
                {"name": arName, "languageId": 2},
            ],
        }

    def addChildTypeList(self):
        countError = 0
        dataList = [
            self.createChildType("pregnant", "Pregnant", "حمل"),
            self.createChildType("child", "Child", "طفل"),
        ]

        for i in dataList:
            childTypeSerializer = ChildTypeSerializer(data=i)
            if childTypeSerializer.is_valid():
                childTypeSerializer.save()

                if "id" in childTypeSerializer.data:
                    for j in i["languageList"]:
                        temp = {}
                        temp["name"] = j["name"]
                        temp["childTypeId"] = childTypeSerializer.data["id"]
                        temp["languageId"] = j["languageId"]

                        childTypeLanguageSerializer = ChildTypeLanguageSerializer(
                            data=temp
                        )
                        if childTypeLanguageSerializer.is_valid():
                            childTypeLanguageSerializer.save()
                        else:
                            countError = countError + 1
                else:
                    countError = countError + 1
            else:
                countError = countError + 1

        if countError == 0:
            return True

        return False

    def createGender(self, keyName, enName, arName):
        return {
            "keyName": keyName,
            "languageList": [
                {"name": enName, "languageId": 1},
                {"name": arName, "languageId": 2},
            ],
        }

    def addGenderList(self):
        countError = 0
        dataList = [
            self.createGender("male", "Male", "ذكر"),
            self.createGender("female", "Female", "أنثى"),
            self.createGender("idk", "I Don't Know", "لا أعرف"),
        ]

        for i in dataList:
            genderSerializer = GenderSerializer(data=i)
            if genderSerializer.is_valid():
                genderSerializer.save()

                if "id" in genderSerializer.data:
                    for j in i["languageList"]:
                        temp = {}
                        temp["name"] = j["name"]
                        temp["genderId"] = genderSerializer.data["id"]
                        temp["languageId"] = j["languageId"]

                        genderLanguageSerializer = GenderLanguageSerializer(data=temp)
                        if genderLanguageSerializer.is_valid():
                            genderLanguageSerializer.save()
                        else:
                            countError = countError + 1
                else:
                    countError = countError + 1
            else:
                countError = countError + 1

        if countError == 0:
            return True

        return False

    def createSymptomType(self, keyName, enName, arName, imagePath):
        filePath = imagePath
        resizedFile = None
        resizeImage = ResizeImage()
        resizedFile = resizeImage.resizeImage(filePath)

        data = {
            "keyName": keyName,
            "image": resizedFile,
            "createdDate": datetime.now(),
            "updatedDate": datetime.now(),
            "languageList": [
                {"name": enName, "languageId": 1},
                {"name": arName, "languageId": 2},
            ],
        }
        return data

    def addSymptomList(self):
        countError = 0
        dataList = [
            self.createSymptomType(
                "back_pain",
                "Back pain",
                "ألم الظهر",
                MEDIA_ROOT+"/add_symptom_type/back_pain.png",
            ),
            self.createSymptomType(
                "bloating", "Bloating", "انتفاخ", MEDIA_ROOT+"/add_symptom_type/bloating.png"
            ),
            self.createSymptomType(
                "contractions",
                "Contractions",
                "انقباضات",
                MEDIA_ROOT+"/add_symptom_type/contractions.png",
            ),
            self.createSymptomType(
                "sore_breasts",
                "Sore breasts",
                "ألم في الثدي",
                MEDIA_ROOT+"/add_symptom_type/sore_breasts.png",
            ),
            self.createSymptomType(
                "constipation",
                "Constipation",
                "إمساك",
                MEDIA_ROOT+"/add_symptom_type/constipation.png",
            ),
            self.createSymptomType(
                "cramping", "Cramping", "تشنجات", MEDIA_ROOT+"/add_symptom_type/cramping.png"
            ),
            self.createSymptomType(
                "diarrhoea",
                "Diarrhoea",
                "إسهال",
                MEDIA_ROOT+"/add_symptom_type/diarrhoea.png",
            ),
            self.createSymptomType(
                "dizziness", "Dizziness", "دوخة", MEDIA_ROOT+"/add_symptom_type/dizziness.png"
            ),
            self.createSymptomType(
                "exhaustion",
                "Exhaustion",
                "إرهاق",
                MEDIA_ROOT+"/add_symptom_type/exhaustion.png",
            ),
            self.createSymptomType(
                "food_aversion",
                "Food aversions",
                "نفور من الطعام",
                MEDIA_ROOT+"/add_symptom_type/food_aversion.png",
            ),
            self.createSymptomType(
                "food_craving",
                "Food cravings",
                "اشتهاء الطعام",
                MEDIA_ROOT+"/add_symptom_type/food_craving.png",
            ),
            self.createSymptomType(
                "frequent_urination",
                "Frequent urination",
                "تبول متكرر",
                MEDIA_ROOT+"/add_symptom_type/frequent_urination.png",
            ),
            self.createSymptomType(
                "headaches", "Headaches", "صداع", MEDIA_ROOT+"/add_symptom_type/headaches.png"
            ),
            self.createSymptomType(
                "heartburn",
                "Heartburn",
                "حرقة المعدة",
                MEDIA_ROOT+"/add_symptom_type/heartburn.png",
            ),
            self.createSymptomType(
                "itching", "Itching", "حكة", MEDIA_ROOT+"/add_symptom_type/itching.png"
            ),
            self.createSymptomType(
                "insomnia", "Insomnia", "أرق", MEDIA_ROOT+"/add_symptom_type/insomnia.png"
            ),
            self.createSymptomType(
                "morning_sickness",
                "Morning sickness",
                "غثيان الصباح",
                MEDIA_ROOT+"/add_symptom_type/morning_sickness.png",
            ),
            self.createSymptomType(
                "pelvic_pain",
                "Pelvic pain",
                "ألم الحوض",
                MEDIA_ROOT+"/add_symptom_type/pelvic_pain.png",
            ),
            self.createSymptomType(
                "spotting",
                "Spotting",
                "نزول نقاط دم",
                MEDIA_ROOT+"/add_symptom_type/spotting.png",
            ),
            self.createSymptomType(
                "stuffy_nose",
                "Stuffy nose",
                "احتقان الأنف",
                MEDIA_ROOT+"/add_symptom_type/stuffy_nose.png",
            ),
            self.createSymptomType(
                "swelling", "Swelling", "تورم", MEDIA_ROOT+"/add_symptom_type/swelling.png"
            ),
            self.createSymptomType(
                "discharge",
                "Discharge",
                "إفرازات",
                MEDIA_ROOT+"/add_symptom_type/discharge.png",
            ),
            self.createSymptomType(
                "other", "Other", "أخرى", MEDIA_ROOT+"/add_symptom_type/other.png"
            ),
        ]

        for i in dataList:
            symptomTypeSerializer = SymptomTypeSerializer(data=i, partial=True)
            if symptomTypeSerializer.is_valid():
                symptomTypeSerializer.save()

                if "id" in symptomTypeSerializer.data:
                    for j in i["languageList"]:
                        temp = {}
                        temp["name"] = j["name"]
                        temp["symptomTypeId"] = symptomTypeSerializer.data["id"]
                        temp["languageId"] = j["languageId"]

                        symptomTypeLanguageSerializer = SymptomTypeLanguageSerializer(
                            data=temp
                        )
                        if symptomTypeLanguageSerializer.is_valid():
                            symptomTypeLanguageSerializer.save()
                        else:
                            countError = countError + 1
                else:
                    countError = countError + 1
            else:
                countError = countError + 1

        if countError == 0:
            return True

        return False

    def createKickTrackerStatus(
        self, keyName, count, color, enName, enDescription, arName, arDescription
    ):
        return {
            "keyName": keyName,
            "count": count,
            "color": color,
            "createdDate": datetime.now(),
            "updatedDate": datetime.now(),
            "languageList": [
                {"name": enName, "description": enDescription, "languageId": 1},
                {"name": arName, "description": arDescription, "languageId": 2},
            ],
        }

    def addKickTrackerStatusList(self):
        countError = 0
        dataList = [
            self.createKickTrackerStatus(
                "warning",
                5,
                "0xFFF44336",
                "Warning",
                "Fewer than 6 movements in 2 hours or no movement during baby's active time — call your doctor immediately.",
                "تحذير",
                "أقل من 6 حركات خلال ساعتين أو عدم وجود حركة في وقت نشاط الجنين — يجب الاتصال بالطبيب فورًا.",
            ),
            self.createKickTrackerStatus(
                "caution",
                6,
                "0xFFFFEB3B",
                "Caution",
                "6 to 9 movements within 2 hours or weaker movements than usual. Monitor closely.",
                "تنبيه",
                "من 6 إلى 9 حركات خلال ساعتين أو حركات أضعف من المعتاد. يجب المراقبة عن قرب.",
            ),
            self.createKickTrackerStatus(
                "caution",
                9,
                "0xFFFFEB3B",
                "Caution",
                "6 to 9 movements within 2 hours or weaker movements than usual. Monitor closely.",
                "تنبيه",
                "من 6 إلى 9 حركات خلال ساعتين أو حركات أضعف من المعتاد. يجب المراقبة عن قرب.",
            ),
            self.createKickTrackerStatus(
                "normal",
                10,
                "0xFF4CAF50",
                "Normal",
                "10 or more movements within 2 hours; consistent with baby's usual pattern.",
                "طبيعي",
                "10 حركات أو أكثر خلال ساعتين؛ متسقة مع نمط حركة الجنين المعتاد.",
            ),
        ]

        for i in dataList:
            kickTrackerStatusSerializer = KickTrackerStatusSerializer(data=i)
            if kickTrackerStatusSerializer.is_valid():
                kickTrackerStatusSerializer.save()

                if "id" in kickTrackerStatusSerializer.data:
                    for j in i["languageList"]:
                        temp = {}
                        temp["name"] = j["name"]
                        temp["description"] = j["description"]
                        temp["kickTrackerStatusId"] = kickTrackerStatusSerializer.data[
                            "id"
                        ]
                        temp["languageId"] = j["languageId"]

                        kickTrackerStatusLanguageSerializer = (
                            KickTrackerStatusLanguageSerializer(data=temp)
                        )
                        if kickTrackerStatusLanguageSerializer.is_valid():
                            kickTrackerStatusLanguageSerializer.save()
                        else:
                            countError = countError + 1
                else:
                    countError = countError + 1
            else:
                countError = countError + 1

        if countError == 0:
            return True

        return False

    def addBMICaseList(self):
        bmiMapList = [
            {
                "keyName": "singletone",
                "createdDate": datetime.now(),
                "updatedDate": datetime.now(),
                "languageList": [
                    {"name": "Singletone", "languageId": 1},
                    {"name": "حمل مفرد", "languageId": 2},
                ],
                "caseList": [
                    {
                        "keyName": "underweight",
                        "min": 0,
                        "max": 18.5,
                        "createdDate": datetime.now(),
                        "updatedDate": datetime.now(),
                        "languageList": [
                            {"name": "Underweight", "languageId": 1},
                            {"name": "نقص الوزن", "languageId": 2},
                        ],
                        "weightGain":{
                            "min": 12.5,
                            "max": 18,
                            "createdDate": datetime.now(),
                            "updatedDate": datetime.now(),
                        }
                    },
                    {
                        "keyName": "normal",
                        "min": 18.5,
                        "max": 24.9,
                        "createdDate": datetime.now(),
                        "updatedDate": datetime.now(),
                        "languageList": [
                            {"name": "Normal", "languageId": 1},
                            {"name": "وزن طبيعي", "languageId": 2},
                        ],
                        "weightGain":{
                            "min": 11.5,
                            "max": 16,
                            "createdDate": datetime.now(),
                            "updatedDate": datetime.now(),
                        }
                    },
                    {
                        "keyName": "overweight",
                        "min": 25,
                        "max": 29.9,
                        "createdDate": datetime.now(),
                        "updatedDate": datetime.now(),
                        "languageList": [
                            {"name": "Overweight", "languageId": 1},
                            {"name": "زيادة في الوزن", "languageId": 2},
                        ],
                        "weightGain":{
                            "min": 7,
                            "max": 11.5,
                            "createdDate": datetime.now(),
                            "updatedDate": datetime.now(),
                        }
                    },
                    {
                        "keyName": "obese",
                        "min": 30,
                        "max": 0,
                        "createdDate": datetime.now(),
                        "updatedDate": datetime.now(),
                        "languageList": [
                            {"name": "Obese", "languageId": 1},
                            {"name": "سمنة", "languageId": 2},
                        ],
                        "weightGain":{
                            "min": 5,
                            "max": 9,
                            "createdDate": datetime.now(),
                            "updatedDate": datetime.now(),
                        }
                    }
                ],
            },
            {
                "keyName": "twin",
                "createdDate": datetime.now(),
                "updatedDate": datetime.now(),
                "languageList": [
                    {"name": "Twin", "languageId": 1},
                    {"name": "حمل بتوأم", "languageId": 2},
                ],
                "caseList": [
                    {
                        "keyName": "underweight",
                        "min": 0,
                        "max": 18.5,
                        "createdDate": datetime.now(),
                        "updatedDate": datetime.now(),
                        "languageList": [
                            {"name": "Underweight", "languageId": 1},
                            {"name": "نقص الوزن", "languageId": 2},
                        ],
                        "weightGain":{
                            "min": 16.8,
                            "max": 24.5,
                            "createdDate": datetime.now(),
                            "updatedDate": datetime.now(),
                        }
                    },
                    {
                        "keyName": "normal",
                        "min": 18.5,
                        "max": 24.9,
                        "createdDate": datetime.now(),
                        "updatedDate": datetime.now(),
                        "languageList": [
                            {"name": "Normal", "languageId": 1},
                            {"name": "وزن طبيعي", "languageId": 2},
                        ],
                        "weightGain":{
                            "min": 16.8,
                            "max": 24,
                            "createdDate": datetime.now(),
                            "updatedDate": datetime.now(),
                        }
                    },
                    {
                        "keyName": "overweight",
                        "min": 25,
                        "max": 29.9,
                        "createdDate": datetime.now(),
                        "updatedDate": datetime.now(),
                        "languageList": [
                            {"name": "Overweight", "languageId": 1},
                            {"name": "زيادة في الوزن", "languageId": 2},
                        ],
                        "weightGain":{
                            "min": 14.1,
                            "max": 22.7,
                            "createdDate": datetime.now(),
                            "updatedDate": datetime.now(),
                        }
                    },
                    {
                        "keyName": "obese",
                        "min": 30,
                        "max": 0,
                        "createdDate": datetime.now(),
                        "updatedDate": datetime.now(),
                        "languageList": [
                            {"name": "Obese", "languageId": 1},
                            {"name": "سمنة", "languageId": 2},
                        ],
                        "weightGain":{
                            "min": 11.3,
                            "max": 19.1,
                            "createdDate": datetime.now(),
                            "updatedDate": datetime.now(),
                        }
                    }
                ],
            }
        ]

        for bmiMapCase in bmiMapList:
            bmiCaseTypeSerializer = BMICaseTypeSerializer(data = bmiMapCase)
            if bmiCaseTypeSerializer.is_valid():
                bmiCaseTypeSerializer.save()

                if "id" in bmiCaseTypeSerializer.data:
                    for bmiCaseTypeLanguage in bmiMapCase["languageList"]:
                        bmiCaseTypeLanguage["bmiCaseTypeId"] = bmiCaseTypeSerializer.data["id"]
                        bmiCaseTypeLanguageSerializer = BMICaseTypeLanguageSerializer(data = bmiCaseTypeLanguage)
                        if bmiCaseTypeLanguageSerializer.is_valid():
                            bmiCaseTypeLanguageSerializer.save()
                    
                    for bmiCase in bmiMapCase["caseList"]:
                        bmiCase["bmiCaseTypeId"] = bmiCaseTypeSerializer.data["id"]
                        bmiCaseSerializer = BMICaseSerializer(data = bmiCase)
                        if bmiCaseSerializer.is_valid():
                            bmiCaseSerializer.save()
                            if "id" in bmiCaseSerializer.data:
                                for bmiCaseLanguage in bmiCase["languageList"]:
                                    bmiCaseLanguage["bmiCaseId"] = bmiCaseSerializer.data["id"]
                                    bmiCaseLanguageSerializer = BMICaseLanguageSerializer(data = bmiCaseLanguage)
                                    if bmiCaseLanguageSerializer.is_valid():
                                        bmiCaseLanguageSerializer.save()

                                weightGain = bmiCase["weightGain"]
                                weightGain["bmiCaseId"] = bmiCaseSerializer.data["id"]
                                bmiCaseWeightGainSerializer = BMICaseWeightGainSerializer(data=weightGain)
                                if bmiCaseWeightGainSerializer.is_valid():
                                    bmiCaseWeightGainSerializer.save()    

        return True

    def createCalculationMethod(self, keyName, enName, arName):
        return {
            "keyName": keyName,
            "languageList": [
                {"name": enName, "languageId": 1},
                {"name": arName, "languageId": 2},
            ],
        }

    def addCalculationMethodList(self):
        countError = 0
        dataList = [
            self.createCalculationMethod("last_period", "Last Period", "آخر دورة شهرية"),
            self.createCalculationMethod("conception_date", "Conception Date", "تاريخ الإخصاب"),
            self.createCalculationMethod("ivf", "IVF", "أطفال الأنابيب"),
            self.createCalculationMethod("ultrasound", "Ultrasound", "الأشعة الصوتية (السونار)"),
        ]

        for i in dataList:
            i["createdDate"] = datetime.now()
            i["updatedDate"] = datetime.now()
            calculateMethodSerializer = CalculationMethodSerializer(data=i)
            if calculateMethodSerializer.is_valid():
                calculateMethodSerializer.save()

                if "id" in calculateMethodSerializer.data:
                    for j in i["languageList"]:
                        temp = {}
                        temp["name"] = j["name"]
                        temp["calculationMethodId"] = calculateMethodSerializer.data["id"]
                        temp["languageId"] = j["languageId"]

                        calculationMethodLanguageSerializer = CalculationMethodLanguageSerializer(data=temp)
                        if calculationMethodLanguageSerializer.is_valid():
                            calculationMethodLanguageSerializer.save()
                        else:
                            countError = countError + 1
                else:
                    countError = countError + 1
            else:
                countError = countError + 1

        if countError == 0:
            return True

        return False

    def addDeviceOSTypeList(self):
        
        dataList = [
            {
                "keyName":"IOS",
            },
            {
                "keyName":"Android"
            }
        ]

        countError = 0
        for i in dataList:
            i["createdDate"] = datetime.now()
            i["updatedDate"] = datetime.now()
            deviceOSTypeSerializer = DeviceOSTypeSerializer(data=i)
            if deviceOSTypeSerializer.is_valid():
                deviceOSTypeSerializer.save()
            else:
                countError = countError + 1
        if countError == 0:
            return True
        return False

    def addParent(self):
        selected = Language.objects.get(id=1)
        parent = Parent(
            phone="+201019340601",
            languageId=selected,
            createdDate=datetime.now(),
            updatedDate=datetime.now(),
        )
        parent.save()
        if parent.id is not None:
            parentDetail = ParentDetail(
                firstName="Test1",
                lastName="Test1",
                email="test_1@gmail.com",
                password="123456",
                createdDate=datetime.now(),
                updatedDate=datetime.now(),
                parentId = parent
            )
            parentDetail.save()
            return True
        return False


    def post(self, request, *args, **kwargs):

        isAdded = self.addTokenTypeList()

        if isAdded:
            isAdded = self.addLanguageList()
        else:
            return JsonResponse(
                {"isSuccess": False, "error": "Token Types list is not added"},
                safe=False,
                status=404,
            )

        if isAdded:
            isAdded = self.addChildTypeList()
        else:
            return JsonResponse(
                {"isSuccess": False, "error": "Language list is not added"},
                safe=False,
                status=404,
            )

        if isAdded:
            isAdded = self.addGenderList()
        else:
            return JsonResponse(
                {"isSuccess": False, "error": "Child Type list is not added"},
                safe=False,
                status=404,
            )

        if isAdded:
            isAdded = self.addSymptomList()
        else:
            return JsonResponse(
                {"isSuccess": False, "error": "Gender list is not added"},
                safe=False,
                status=404,
            )

        if isAdded:
            isAdded = self.addKickTrackerStatusList()
        else:
            return JsonResponse(
                {"isSuccess": False, "error": "Symptom Types list is not added"},
                safe=False,
                status=404,
            )
        
        if isAdded:
            isAdded = self.addBMICaseList()
        else:
            return JsonResponse(
                {"isSuccess": False, "error": "Track Status list is not added"},
                safe=False,
                status=404,
            )
        
        if isAdded:
            isAdded = self.addCalculationMethodList()
        else:
            return JsonResponse(
                {"isSuccess": False, "error": "BMI Case list is not added"},
                safe=False,
                status=404,
            )
        
        if isAdded:
            isAdded = self.addDeviceOSTypeList()
        else:
            return JsonResponse(
                {"isSuccess": False, "error": "Calculation method list is not added"},
                safe=False,
                status=404,
            )

        if isAdded:
            isAdded = self.addParent()
        else:
            return JsonResponse(
                {"isSuccess": False, "error": "Device OS Type List is not Added"},
                safe=False,
                status=404,
            )

        if isAdded == False:
            return JsonResponse(
                {"isSuccess": False, "error": "Can not add Parent"},
                safe=False,
                status=404,
            )

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

