import json
import requests
from django.contrib.auth.models import Permission
from django.core.mail import EmailMultiAlternatives
import concurrent.futures
import threading
from django.core.mail import EmailMessage
from django.forms import model_to_dict
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.db import IntegrityError, connection
from django.template.loader import render_to_string
from django.views.decorators.cache import never_cache
from django.core.cache import caches, cache
try: # for pip >= 10
    from pip._internal.req.req_install import logger
except ImportError: # for pip <= 9.0.3
    from pip.req.req_install import logger

from rest_framework.decorators import api_view, authentication_classes
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
from Subscriber.Authentication import SessionAuthentication, IsAuthenticated, StartFitSessionUtil
from Subscriber.models import User
from utility.models import Intensity, Roles, UserRoles, PartnerType, Country, PlanPurposes, PlanAbilities,PriceMapping,Partners,PriceConversion,Science
import csv
import json
from Plan.models import Plan


def maxRepsPerSt(request):
    Reps={}
    lookuptable_key="Reps"
    cachesession=cache.get(lookuptable_key)
    if cachesession:
        print("in cache")
        Reps=cachesession
        return JsonResponse({"sucess":True,"data":Reps['dataArr'],"powerData":Reps['intensityData']})

    else:    
        data = Intensity.objects.all()
        print(data)
        dataArr = []
        intensityData = []
        for dt in data:
            dataObj = model_to_dict(dt)
            #print(dataObj)
            dataArr.append(dataObj)
        for dt1 in data:
            dataObj = model_to_dict(dt1)
            if dataObj['intensity'] <= 50:
                dataObj['maxValue'] = 2
                dataObj['medValue'] = 4
                dataObj['minValue'] = 8
            if dataObj['intensity'] >50 and dataObj['intensity'] <=60:
                dataObj['maxValue'] = 2
                dataObj['medValue'] = 3
                dataObj['minValue'] = 4
            if dataObj['intensity'] >60 and dataObj['intensity'] <=70:
                dataObj['maxValue'] = 1
                dataObj['medValue'] = 2
                dataObj['minValue'] = 3
            if dataObj['intensity'] >70 and dataObj['intensity'] <=80:
                dataObj['maxValue'] = 1
                dataObj['medValue'] = 1
                dataObj['minValue'] = 2
            if dataObj['intensity'] >80 and dataObj['intensity'] <=100:
                dataObj['maxValue'] = 1
                dataObj['medValue'] = 1
                dataObj['minValue'] = 1
            intensityData.append(dataObj)
            #print(dataObj['intensity'],"123")
            #print(dataObj['maxValue'],"456")
            #print(dataObj['modValue'],"789")
        Reps['intensityData']=intensityData
        Reps['dataArr']=dataArr   
        cache.set(lookuptable_key,Reps)    
        return JsonResponse({"sucess":True,"data":dataArr,"powerData":Reps['intensityData']})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def createRoles(request):
    #user = request.session['user_id']
    #print(user)
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user=username['id']
    roleInfo = json.loads(request.body.decode('utf-8'))
    req=roleInfo
    url="utility/createrole"
    try:
        if username != None:
            roleDetails = Roles.objects.filter(role = roleInfo['roleInf']['role'])
            if roleDetails.exists():
                return JsonResponse({"success":False,"message":"Role Already exists"})
            roles = Roles.objects.create(
                role = roleInfo['roleInf']['role']
            )
            roles.save()
            return JsonResponse({"success":True,"message":"Role Saved Successfully"})
        else:
            return JsonResponse({"success":False,"message":"User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def getRoles(request):
    #user = request.session['user_id']
    #print(user)
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    print(username)
    user = username['id']
    req="GET"
    url="utility/getuserroles"
    try:
        if username != None:
            roleArr = list()
            userArr = list()
            roledata = Roles.objects.values('id', 'role')
            userData = User.objects.values('id','username')
            for dt in roledata:
                data = (dt)
                roleArr.append({'id': data['id'], 'role': data['role']})
            for dt in userData:
                data = (dt)
                userArr.append({'id': data['id'], 'username': data['username']})
            return JsonResponse({"roles":roleArr,"users":userArr})
        else:
            return JsonResponse({"success":False,"message":"User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def createUserRoles(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    roleInfo = json.loads(request.body.decode('utf-8'))
    req=roleInfo
    url="utility/createuserrole"
    try:
        if username != None:
            roleDetails = Roles.objects.filter(role = roleInfo['roleInf']['role'])
            if roleDetails.exists():
                return JsonResponse({"success":False,"message":"Role Already exists"})
            roles = UserRoles.objects.create(
                roles_id = roleInfo['roleInf']['role'],
                user_id = roleInfo['roleInf']['user']
            )
            roles.save()
            return JsonResponse({"success":True,"message":"Role Saved Successfully"})
        else:
            return JsonResponse({"success":False,"message":"User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def termsAndConditions(request):
    try:
        return JsonResponse({"success": True, "content": "<h2><li>Who we are </li></h2>Stratfit is the world's first scientifically designed and developed fitness platform. <br>It allows elite strength coaches to design and construct training programmes and publish them to the world in the form of an easy to use app for Android and Iphone users. <br>All programmes in Stratfit are auto regulated real time according to users feedback. <br>Stratfit's mobile app is a virtual expert trainer.<br>We aim to be the most trusted and reliable platform for fitness interactions and help users transform their lives - fitness and beyond."})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg":str(e)})

def officeMail(subject,message,to_email):
    '''count = SentEmailsCount.objects.all()
    for val in count:
        values = model_to_dict(val)
        if values['count'] < 9500:
            FROM_EMAIL = values['email_id']
            break'''
    FROM_EMAIL = "teamdentalsuite360@gmail.com"
    print(FROM_EMAIL,"1234565434566543456765434")
    msg = EmailMultiAlternatives(subject, message, FROM_EMAIL, [to_email])
    msg.attach_alternative(message, "text/html")
    msg.send()
    '''emailCount = SentEmailsCount.objects.get(email_id = FROM_EMAIL)
    increaseCount = int(emailCount.count)+1
    emailCount.count = increaseCount
    emailCount.save()'''

@never_cache
def getPartnerType(request):
    partnertype={}
    lookuptable_key="partner"
    cachesession=cache.get(lookuptable_key)
    if cachesession:
        print("in cache")
        partnertype=cachesession
        return JsonResponse({"success":True,"details":partnertype['dataArr']})
    else:
        dataArr = []
        partnerType = PartnerType.objects.values('id','partnerTypeName')
        for partner in partnerType:
            partnerObj = dict(partner)
            dataArr.append(partnerObj)
        partnertype['dataArr']=dataArr 
        cache.set(lookuptable_key,partnertype)   
        return JsonResponse({"success":True,"details":partnertype['dataArr']})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def getcountrydata(request):
    stratsessionutil = StartFitSessionUtil()
    countrydata={}
    lookuptable_key="getcountrydata"
    cachesession=cache.get(lookuptable_key)
    if cachesession:
        countrydata=cachesession
        print("in cache")
        try:
            username = stratsessionutil.get_user_insession(request)
            print(username)
            if username!=None:
                return HttpResponse(json.dumps(countrydata['dataArr']))
            else:
                return JsonResponse({"success":False,"message":"User logged out"})
        except Exception as e:
            logger.exception("something wrong")
            return JsonResponse({"msg": str(e)}) 
    else:
        username = stratsessionutil.get_user_insession(request)
        print(username)
        if username != None:
            data = Country.objects.values('id','name','countryCode','dialCode').filter(countryStatus=1).order_by('name')
            dataArr = []
            for dt in data:
                dataObj = dict(dt)
                dataArr.append(dataObj)
            countrydata['dataArr']=dataArr 
            cache.set(lookuptable_key,countrydata)   
            return HttpResponse(json.dumps(countrydata['dataArr']))
        else:
            return JsonResponse({"success": False, "message": "User logged out"})
    '''except Exception as e:
        logger.exception("something wrong getting countries")
        return JsonResponse({"msg": str(e)})'''

@never_cache
def getPlanPurposes(request):
    purposesInfo={}
    lookuptable_key="planPurposes"
    cachesession=cache.get(lookuptable_key)
    if cachesession:
        print("in cachesession")
        purposesInfo=cachesession
        return JsonResponse({"goals": purposesInfo['goals']}) 
        
    else:
        goals = []
        puroses= PlanPurposes.objects.values('id','GoalName','parentGoalName_id').filter(parentGoalName_id__isnull=True)
        for pp in puroses:
            ppObj = dict(pp)
            #goals.append(ppObj)
            purposes1 = PlanPurposes.objects.filter(parentGoalName_id = ppObj['id']).values('id','GoalName','parentGoalName_id')
            if purposes1.exists():
                childArr=[]
                for val in purposes1:
                    valObj = dict(val)
                    childArr.append(valObj)
                    ppObj['subGoals'] = childArr
                    #goals.append(ppObj)
                    purposes2 = PlanPurposes.objects.filter(parentGoalName_id = valObj['id']).values('id','GoalName','parentGoalName_id')
                    if purposes2.exists():
                        childArr1=[]
                        for val2 in purposes2:
                            val2Obj = dict(val2)
                            childArr1.append(val2Obj)
                            valObj['subGoals1']=childArr1
                            #goals.append(ppObj)
                            purposes3 = PlanPurposes.objects.filter(parentGoalName_id = val2Obj['id']).values('id','GoalName','parentGoalName_id')
                            if purposes3.exists():
                                childArr2=[]
                                for val3 in purposes3:
                                    val3Obj = dict(val3)
                                    childArr2.append(val3Obj)
                                    val2Obj['subGoals2'] = childArr2
            goals.append(ppObj)
        purposesInfo['goals']=goals
        cache.set(lookuptable_key,purposesInfo)
        return JsonResponse({"goals": purposesInfo['goals']})

@never_cache
def getPlanAbilities(request):
    abilitiesdata={}
    lookuptable_key="abilities"
    cachesession=cache.get(lookuptable_key)
    if cachesession:
        print("here in cache")
        abilitiesdata=cachesession
        return JsonResponse({"abilities": abilitiesdata['abilities']})
    else:    
        abilities = []
        puroses= PlanAbilities.objects.values().exclude(id = 16)
        for pp in puroses:
            ppObj = dict(pp)
            abilities.append(ppObj)
        abilitiesdata['abilities']=abilities
        cache.set(lookuptable_key,abilitiesdata)   
        return JsonResponse({"abilities":abilitiesdata['abilities']})

@never_cache
def getPlanGoalValues(request):
    goalValues={}
    lookuptable_key="plangoals"
    cachesession=cache.get(lookuptable_key)
    if cachesession:
        print("in cache")
        goalValues=cachesession
        return JsonResponse({"goals": goalValues['goals']})
        
    else:    
        goals = []
        puroses= PlanPurposes.objects.values()
        for pp in puroses:
            ppObj = dict(pp)
            goals.append(ppObj)
        goalValues['goals']=goals 
        cache.set(lookuptable_key,goalValues)   
        return JsonResponse({"goals": goalValues['goals']})

@never_cache
def getPlanIDS(request):
    plans={}
    lookuptable_key="planIDS"
    cachesession=cache.get(lookuptable_key)
    if cachesession:
        print("in cache")
        plans=cachesession
        return JsonResponse({"plans": plans['goals']})
    else: 
        print("here")  
        goals = []
        puroses= Plan.objects.values()
        for pp in puroses:
            ppObj = dict(pp)
            goals.append(ppObj)
        plans['goals']=goals
        cache.set(lookuptable_key,plans)    
        return JsonResponse({"plans": plans['goals']})

def insertPriceArr(request):
    inrArr = [0,80,160,250,300,400,500,550,600,700,800,850,900,1000,1100,1200,1250,1300,1400,1500,1600,1650,1700,1800,1900,1950,2000,2100,2200,2250,2300,2400,2500,2600,2650,2700,2800,2900,2950,3000,3100,3200,3250,3300,3400,3500,3600,3700,3800,3900,4000,4500,4900,5200,5500,5900,6200,6500,6900,7500,7900,8500,8900,9500,9900,10900,11900,12500,12900,13500,13900,14900,15500,15900,16900,17900,18900,19900,24900,27900,29900,34900,39900,44900,54900,59900,69900,79900]
    usdArr = [0,0.99,1.99,2.99,3.99,4.99,5.99,6.99,7.99,8.99,9.99,10.99,11.99,12.99,13.99,14.99,15.99,16.99,17.99,18.99,19.99,20.99,21.99,22.99,23.99,24.99,25.99,26.99,27.99,28.99,29.99,30.99,31.99,32.99,33.99,34.99,35.99,36.99,37.99,38.99,39.99,40.99,41.99,42.99,43.99,44.99,45.99,46.99,47.99,48.99,49.99,54.99,59.99,64.99,69.99,74.99,79.99,84.99,89.99,94.99,99.99,109.99,119.99,124.99,129.99,139.99,149.99,159.99,169.99,174.99,179.99,189.99,199.99,209.99,219.99,229.99,239.99,249.99,299.99,349.99,399.99,449.99,499.99,599.99,699.99,799.99,899.99,999.99]
    for inr,usd in zip(inrArr,usdArr):
        pricemapCreate = PriceMapping.objects.create(
            inr = inr,
            usd = usd
        )
        pricemapCreate.save()
    return JsonResponse({"success": True,"message":"records inserted successfully"})

def getpriceMap(request):
    price={}
    lookuptable_key="getpriceMap"
    cachesession=cache.get(lookuptable_key)
    if cachesession:
        print("in cache")
        price=cachesession
        return JsonResponse({"success":True,"details":price['priceMap']})

    else:
        print("here")    
        getpriceMapValues = PriceMapping.objects.values()
        priceMap ={}
        for val in getpriceMapValues:
            valObj = dict(val)
            priceMap[int(valObj['inr'])] = valObj['usd']
            #priceMap.append({valObj['inr']:valObj['usd']})
        price['priceMap']=priceMap    
        cache.set(lookuptable_key,price)
        return JsonResponse({"success":True,"details":price['priceMap']})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def createPartners(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    try:
        if username != "":
            user = username['id']
            details  = json.loads(request.body.decode('utf-8'))
            createPartner  = Partners.objects.create(
                partnerName = details['campInfo']['partnerName'],
                partnerImage = details['campInfo']['img'],
                createdBy_id = user,
                modifiedBy_id = user
            )
            if 'http' in details['campInfo']['url']:
                createPartner.partnerLink = details['campInfo']['url']
            else:
                createPartner.partnerLink = "http://"+details['campInfo']['url']
            createPartner.save()
    except Exception as e:
        logger.exception("something wrong getting countries")
        return JsonResponse({"msg": str(e)})

def getCurrentCurrency(request):
    apifixer = "http://api.fixer.io/latest?base=USD"
    postObj2 = requests.get(apifixer)
    postDetail12 = postObj2.json()
    inrValue1 = postDetail12['rates']['INR']
    priceDetails = PriceConversion.objects.get(id=1)
    if priceDetails:
        priceDetails.inrValue = inrValue1
        priceDetails.save()
    return JsonResponse({"success":True})
    #print(currencyType, "currencyType")

    
def validateEmail( email ):
    from django.core.validators import validate_email
    from django.core.exceptions import ValidationError
    try:
        validate_email( email )
        return True
    except ValidationError:
        return False

def userQuestions(request):
    
    try:
        info=json.loads(request.body.decode('utf-8'))
        emailInfo=info['email']
        nameInfo=info['fname']
        infocode=info['user_question']
        infophone=info['phone']
        user= validateEmail(emailInfo)
        print(user,"gggggggggggggggggggggggg")  
        if user:
            def mail(user):
                return user
            def feedback(infocode,emailInfo):    
                mailContent = infocode
                subject = "Query From User"
                FROM_EMAIL = "admin@stratfit.in"
                email=EmailMessage(subject,mailContent,FROM_EMAIL,['info@stratfit.co'],headers={'Reply-To':emailInfo})
                email.send()
                return infocode
            with concurrent.futures.ThreadPoolExecutor() as executor:
                future=executor.submit(mail,user)
                rand=future.result() 
            t2=threading.Thread(target=feedback,args=(infocode,emailInfo,))
            t2.start()    
            return JsonResponse({"success":True,"message":"Thank you for contacting us we will be back"})
        else:
            return JsonResponse({"success":False,"message":"Please enter valid email"})
    except Exception as e:
        logger.exception("something wrong getting countries")
        return JsonResponse({"msg": str(e)})
 

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def Science_blog(request):
    stratsessionutil = StartFitSessionUtil()
    try:
        username = stratsessionutil.get_user_insession(request)
        info = json.loads(request.body.decode('utf-8'))
        user = username['id']
        if username != None:
            if 'id' in info and info['id']!= None:
                blog=Science.objects.filter(id=info['id'])
                if blog.exists():
                    Blog=Science.objects.get(id=info['id'])
                    if 'name' in info and info['name']!= None:
                        Blog.name=info['name']
                    if 'link' in info and info['link']!= None:
                        Blog.blog_link=info['link']
                    if 'status' in info and info['status']!=None:
                        Blog.status=info['status']
                    Blog.save()    
                return JsonResponse({"success":True,"message":"Blog saved successfully"})        
            else:
                array=[]
                science={}
                Blog=Science.objects.filter(name=info['name'],status=1)
                if Blog.exists():
                    return JsonResponse({"success":True,"message":"user already exists please give the id"})
                else:
                    Blog=Science.objects.create(name=info['name'],blog_link=info['link'],status=1)
                    Blog.save()
                    link=model_to_dict(Blog)
                    print(link['status'])
                    science['id']=link['id']
                    science['name']=link['name']
                    science['blog_link']=link['blog_link']
                    science['status']=link['status']
                    array.append(science)
                       
                    return JsonResponse({"success":True,"message":"Blog successfully saved","link_info":array})   

        else:
            return JsonResponse({"success":False,"message":"user logged out"})

    except Exception as e:
        logger.error("error")
        return JsonResponse({"msg": str(e),"success":False})  

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def remove_link(request):
    stratsessionutil = StartFitSessionUtil()
    try:
        username = stratsessionutil.get_user_insession(request)
        info = json.loads(request.body.decode('utf-8'))
        user = username['id']
        if username != None:
            if 'id' in info and info['id']!= None:
                blog=Science.objects.filter(id=info['id']).update(status=0)
                if blog:
                    return JsonResponse({"success":True,"message":"link deleted successfully"})
                else:
                    return JsonResponse({"success":False,"message":"enter valid id"})    
            else:
                return JsonResponse({"success":False,"message":"enter the id"})    
        else:
            return JsonResponse({"success":False,"message":"user logged out"})

    except Exception as e:
        logger.error("error")
        return JsonResponse({"msg": str(e),"success":False}) 

@api_view(['GET', 'POST'])
@never_cache
def linkslist(request):
    
    try:
        info = json.loads(request.body.decode('utf-8'))
        array=[]
        list={}
        link=Science.objects.filter(status=1)
        for dt in link:
            blog=model_to_dict(dt)
            list['id']=blog['id']
            list['name']=blog['name']
            list['blog_link']= blog['blog_link']
            list['status']= blog['status']
            array.append(list)
            list={}
        return JsonResponse({"success":True,"message":array})                    
       
    except Exception as e:
        logger.error("error")
        return JsonResponse({"msg": str(e),"success":False})  






