import base64
from datetime import datetime
from email.mime.image import MIMEImage
from django.shortcuts import redirect
from django.db import IntegrityError, connection
from django.db.models import F
from django.conf import settings
#import jwt
import requests
from logging import exception
from random import choice
import binascii
from urllib.parse import parse_qsl
#from django.shortcuts import render_to_response
from django.template.loader import get_template
from rest_framework import status
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import logout
from django.contrib.auth.hashers import make_password, check_password
#from django.contrib.sites import requests
import requests
import concurrent.futures
import threading
from django.core.cache import caches, cache
from django.forms import model_to_dict
from django.template import RequestContext, Context ,loader
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 django.core.exceptions import ObjectDoesNotExist    
from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
from django.core.mail import send_mail, EmailMessage, EmailMultiAlternatives
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.response import Response
from requests_oauthlib import OAuth1,OAuth1Session,OAuth2
from social_django.utils import load_backend, psa
from social_django.views import _do_login
from Plan.models import Plan, PlanRating, DraftedPlan, PlanVideos, PlanSession, PlanGoals, SelectedAbilities
from Program.models import Plan as ProgramPlan, PlanRating as ProgramPlanRating, DraftedPlan as ProgramDraftedPlan, PlanVideos as ProgramPlanVideos, PlanGoals as ProgramPlanGoals, SelectedAbilities as ProgramSelectedAbilities
from StratFit import settings
from rest_framework import permissions
import json
from StratFit.settings import BASE_DIR, PAGING_ROWS
from StratFitOrganization.models import Organization, CampainUrls
from Subscriber.serializers import AuthResponseSerializer
from Subscriber.models import User,UserAddress,UserPhoto, FitnessProfile,trainerProfile,trainerVideos,goals, Userfollow, \
    Invitations, SocialProfile, AccountDetails, UserReferral, UserLikes, UserPlateWeight,UsersValidSessions, \
    CampaignDetails, News_letter
from Userplan.models import UserPlan, UserTestPlan, UserSets, UserExercise
from UserProgram.models import UserPlan as ProgramUserPlan, UserTestPlan as ProgramUserTestPlan
from Subscriber.Authentication import StartFitAuthentication,SessionAuthentication,StartFitSessionUtil, AuthResponse
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.response import Response
from Subscriber.Authentication import StartFitAuthentication,SessionAuthentication,StartFitSessionUtil, AuthResponse,IsAuthenticated
from django.views.decorators.cache import never_cache
from django.template.loader import render_to_string, get_template
from datetime import date
from datetime import datetime, timedelta, time
from dateutil.relativedelta import relativedelta
import csv
#import jwt
import requests

from datetime import timedelta
from django.conf import settings
#from social_core.backends.oauth import BaseOAuth2
#from social_core.utils import handle_http_errors
from campaign.models import CampaignFeed
from utility.models import Country,PriceMapping,PriceConversion,AppVersion, TmaxLookup
from django.core.mail import send_mail, EmailMultiAlternatives, EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from datetime import datetime
from utility.views import officeMail
from django.utils import timezone
from django.contrib.gis.geoip2 import GeoIP2


def send_mail(request):
    subject="Exception Details"
    from_email = "admin@stratfit.net"
    to_email = 'soubhik.g@stratfit.co'
    message = "<p>,dfgkdfj slkjg dlfgj gj</p>"
    msg = EmailMultiAlternatives(subject, message, from_email, [to_email])
    msg.attach_alternative(message, "text/html")
    msg.send()

def exceptionMail(user,req,url,err):
    print(user,'+++++')
    print(req,'============')
    print(url)
    print(err)
    #print(datetime.now())
    subject="Exception Details"
    to_email = 'errors@stratfit.co'
    ctx = {
        'URL':url,
        'Request':req,
        'UserID':user,
        'Error':err,
        'Time': datetime.now(),
        #'Build':''
    }
    message = render_to_string('exceptiondetails.html', ctx)
    officeMail(subject, message, to_email)

def register(request):
    try:
        vidata={}
        data=[]
        userObjData = json.loads(request.body.decode('utf-8'))
        if User.objects.filter(email=userObjData['email']).exists():
                    return JsonResponse({"success": False, "message": 'Account with this E-Mail already exists'})
        else:            
            def store(userObjData):
                referalMsg = True
                if 'referalcode' in userObjData and userObjData['referalcode']!='':
                    referalcode = userObjData['referalcode']
                    print(referalcode)
                    ref = UserReferral.objects.values('id','user_id','referralCode').filter(referralCode = referalcode)
                    if ref.exists():
                        for dt in ref:
                            rcode = dt['referralCode']
                            ruserid = dt['user_id']
                            if rcode == referalcode:
                                refferedUserid = ruserid
                                referalMsg = True
                    else:
                        referalMsg = False
                else:
                    refferedUserid = ''
                    
                if referalMsg == False:
                    return JsonResponse({"success": False, "message": 'Invalid Referral Code'})
                else:
                    if User.objects.filter(email=userObjData['email']).exists():
                        return JsonResponse({"success": False, "message": 'Account with this E-Mail already exists'})
                    else:
                        if 'password' in userObjData:
                            passwd = userObjData['password']
                        else:
                            passwd = '123abc'
                        if 'phone' in userObjData:
                            phone = userObjData['phone']
                        else:
                            phone = ''
                        userData = User.objects.create(
                            userType = 2,
                            first_name=userObjData['fname'],
                            email=userObjData['email'],
                            username=userObjData['email'],
                            #currencyType="USD",
                            referUser_id = refferedUserid
                        )
                        if 'currencytype' in userObjData and userObjData['currencytype'] !='':
                            userData.currencyType = userObjData['currencytype']
                        else:
                            userData.currencyType = "USD"
                        if 'company' in userObjData and userObjData['company'] =='pink':
                            userData.company_id = 2
                        else:
                            userData.company_id = 1
                        if 'lname' in userObjData and userObjData['lname'] !='':
                            userData.last_name = userObjData['lname']
                        if phone !='':
                            userData.phone = phone
                        if 'ip' in userObjData and userObjData['ip'] != '':
                            userData.ip = userObjData['ip']
                        if 'deviceType' in userObjData and userObjData['deviceType'] != '':
                            userData.deviceType = userObjData['deviceType']
                        userData.save()
                        userId = userData.id
                        userData.createdBy_id = userId
                        userData.modifiedBy_id = userId
                        userData.save()
                        randomCode = ''.join(choice('0123456789') for i in range(4))
                        rand=str(randomCode)
                        #if 'country' in userObjData and userObjData['country'] != '':
                        #countryID = Country.objects.get(name = userObjData['country'] )
                        '''
                        g = GeoIP()
                        ip = request.META.get('REMOTE_ADDR', None)
                        if ip:
                            country = g.country(ip)['country_name']
                        else:
                        '''    
                        country = 'India'  # default city
                        countryID = Country.objects.get(name=country)
                        counrtycode = countryID.dialCode
                        if countryID:
                            userCountry = UserAddress.objects.create(
                                user_id=userId,
                                country=countryID.id
                            )
                            userCountry.save()
                        else:
                            userCountry = UserAddress.objects.create(
                                user_id = userId,
                                country = 190
                            )
                            userCountry.save()
                        invitedUsers = Invitations.objects.filter(email =userData.email).values()
                        if invitedUsers.exists():
                            updateUser = User.objects.get(id=userId)
                            updateUser.userType = 3
                            updateUser.save()
                        randomCode1 = ''.join(choice('0123456789') for i in range(4))
                        randcode1 = str(randomCode1)
                        userref = UserReferral.objects.create(
                            user_id = userId,
                            referralCode = randcode1,
                            status = 1
                        )
                        userref.save()
                        vidata=userData
                        randnum=rand
                        data.append(vidata)
                        data.append(randnum)

                    return data    
                    
            def mail(data,passwd): 
                print("asdfghj")
                c=data[0]
                rand=data[1]
                instanceSub = User.objects.get(id=c.id)
                #instanceSub.phoneCode = counrtycode[1:]
                #randomCode = ''.join(choice('0123456789') for i in range(4))
                #print(randomCode)
                #rand = str(randomCode)
                
                secret_code_plain = instanceSub.email + '#' + str(data[1])
                secret_code_encode = base64.b64encode(secret_code_plain.encode('ascii'))
                #print(secret_code_encode)
                validateLink = request.META['HTTP_HOST']
                link = "http://"+validateLink+"/services/services/stratservices/subscriber/accountValidateNew1?code=" + secret_code_plain
                subject = "Account Activation"
                to_email = instanceSub.email
                ctx={
                    'first_name':instanceSub.first_name,
                    'link':link,
                    'rand':rand
                }
                message = render_to_string('emailverfication.html',ctx)
                officeMail(subject, message, to_email)
                instanceSub.secretCode = secret_code_encode
                instanceSub.password = make_password(passwd)
                instanceSub.otp = data[1]
                instanceSub.is_active = 0
                instanceSub.save()
                fitnessprofile = FitnessProfile.objects.create(
                    user_id = c.id
                )
                #fitnessprofile.gender = 1
                #fitnessprofile.dob = '1990-01-01'
                #fitnessprofile.height = 175
                #fitnessprofile.heightUnit = 'cms'
                #fitnessprofile.weight = 70
                #fitnessprofile.weightUnit = 'kgs'
                #fitnessprofile.save()
                otp=instanceSub.otp
                return otp
        passwd=userObjData['password'] 
        with concurrent.futures.ThreadPoolExecutor() as executor:
            future=executor.submit(store,userObjData)
            cid=future.result() 
              
        t2=threading.Thread(target=mail,args=(cid,passwd,)) 

        t2.start()    
        return JsonResponse({"success": True, "message": " Account Created successfully, please check your mail. Use " + cid[1]+  "as OTP"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg":str(e)})

def New_Mail(request):
    import time
    try:
        userObjData = json.loads(request.body.decode('utf-8'))
        instanceSub = User.objects.get(email=userObjData['email'])
        
        if instanceSub:
            email=instanceSub.email
            New_email=email.split("@")[0]
            newemail=email.split("@")[1]
            milli_sec =int(round(time.time() * 1000))
            append_str='.'+str(milli_sec)+'@'
            Mail= (New_email)+str(append_str)+newemail
            instanceSub.email=Mail
            instanceSub.save()
            ID =instanceSub.id
            social=SocialProfile.objects.filter(user_id=ID).delete()

            return JsonResponse({"message":Mail})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg":str(e)})




def validateOTP(request):
    userObjData = json.loads(request.body.decode('utf-8'))
    print(userObjData)
    try:
        instance = User.objects.filter(otp = userObjData['otp'])
        #print(instance,"pppp")
        if instance.exists():
            instanceSub = User.objects.get(otp = userObjData['otp'],email=userObjData['email'])
            instanceSub.is_active = 1
            instanceSub.save()
            return JsonResponse({"success": True, "message": "Valid Email"})
        else:
            return JsonResponse({"success": False, "message": "Invalid OTP"})
    except exception as e:
        logger.error("Problem with Update User")
        return JsonResponse({"success": False, "message": str(e)})


def ionicotpvalidate(request, format=None):
    if request.method == 'GET':
        return JsonResponse({'message': 'Please use POST with applicable JSON for login service'})
    elif request.method == 'POST':
        userObjData = json.loads(request.body.decode('utf-8'))
        try:
            instance = User.objects.filter(email=userObjData['email']).filter(otp=userObjData['code'])
            if (instance.exists()):
                return JsonResponse({"success":True, "message":"valid otp","status":1})
            else:
                return JsonResponse({"success": False,"message":"Invalid OTP", "status": 2})
        except exception as e:
            logger.error("Problem with ionic otp")
            return JsonResponse({"success": False, "message": str(e)})
    else:
        return JsonResponse({'message': 'Please use POST with applicable JSON for login service'})

@never_cache
def accountValidateNew(request, format=None):
    secretCode = request.GET['code']
    print(secretCode)
    userData = User.objects.filter(email = secretCode).values('is_active','id','userType')
    if userData.exists():
        for dt in userData:
            userid = dt['id']
            activeStatus = dt['is_active']
            if activeStatus == 1:
                return redirect("http://stratfit.net/")
            else:
                updateuser = User.objects.get(pk = userid)
                updateuser.is_active = 1
                updateuser.save()
                subject = "Welcome to StratFit"
                to_email = updateuser.email
                ctx = {
                    'first_name': updateuser.first_name
                }
                message = render_to_string('welcome.html', ctx)
                officeMail(subject, message, to_email)
                return redirect("http://stratfit.net/")
    else:
        return JsonResponse({"Message":"Please Provide a valid Information"})

def accountValidate(request, format=None):
    lookup_field = 'email'
    model = User
    if request.method == 'GET':
        return JsonResponse({'message' : 'Please use POST with applicable JSON for login service'})
    elif request.method == 'POST':
        userObjData = json.loads(request.body.decode('utf-8'))
        #print(userObjData)
        try:
            try:
                base64.b64decode(userObjData['code'])
                print()
            except binascii.Error:
                return JsonResponse({"success":False, "message":"Wrong Code"})
            codeDecode = base64.b64decode(userObjData['code']).decode("ascii")
            #print(codeDecode)
            codeDecodeSplit = codeDecode.split('#', 1)
            #print(codeDecodeSplit[0],"hhhh")
            instance = User.objects.filter(email=codeDecodeSplit[0]).filter(secretCode=userObjData['code'])
            #print(instance,"pppp")
            if(instance.exists()):
                instanceSub = User.objects.get(email=codeDecodeSplit[0])
                instanceSub.is_active = 1
                instanceSub.save()
                return JsonResponse({"success":True, "message":"Valid Email", "email":codeDecodeSplit[0]})
            else:
                return JsonResponse({"success":False, "message":"Sorry, This is not a valid information, contact admin."})
        except exception as e:
            logger.error("Problem with Update User")
            return JsonResponse({"success": False, "message":str(e)})
    else:
        return JsonResponse({'message': 'Please use POST with applicable JSON for login service'})
        #return JsonResponse({"success":"true"})

def accountValidateOTP(request, format=None):
    lookup_field = 'email'
    model = User
    if request.method == 'GET':
        return JsonResponse({'message' : 'Please use POST with applicable JSON for login service'})
    elif request.method == 'POST':
        userObjData = json.loads(request.body.decode('utf-8'))
        #print(userObjData)
        try:
            instance = User.objects.filter(email=userObjData['email']).filter(otp=userObjData['code'])
            #print(instance,"pppp")
            if(instance.exists()):
                instanceSub = User.objects.get(email=userObjData['email'])
                instanceSub.is_active = 1
                print("here Iam")
                instanceSub.save()
                stratauthentication = StartFitAuthentication()
                loginResponse = stratauthentication.authenticate(instanceSub.email)
                userDataObj = loginResponse
                print(userDataObj)
                try:
                    queryset = User.objects.get(email=userObjData['email'])
                    username = queryset.first_name
                    print(queryset.email)
                    '''for userObj in user:
                        uid = model_to_dict(userObj)
                        print(uid)
                    userRoleID = None'''
                    if queryset.email is not None:
                        request.session['loggedIn'] = True
                        request.session['email'] = queryset.email
                        request.session['user_id'] = queryset.id
                        request.session['first_name'] = queryset.first_name
                        request.session['is_superuser'] = queryset.is_superuser
                        return JsonResponse({"success":True,"message": "Logged In successfully", "profile":[], "goals":[], "tmax":[], "plans":[], "isProfileSet":False, "isGoalSet":False, "isPlanSet":False, "isTmaxSet":False, "code":userObjData['code'],"sessiontoken":loginResponse['sessiontoken'],"userDetails":queryset.email,"username":username,"fname":queryset.first_name,"is_superuser":queryset.is_superuser,"is_active":queryset.is_active,"user_id":queryset.id,"otp":queryset.otp})

                        #instanceSub.is_active = 1
                        #print("here Iam")
                        #instanceSub.save()
                except Exception as e:
                    JsonResponse("Login attempt failed with user", safe=False)
                    authResponse = AuthResponse()
                    authResponse.code = 401
                    authResponse.message = "Invalid_Credentials"
                    return JsonResponse({"success": False, "message": str(e)})
                #return JsonResponse({"success":True, "message":"Valid Email", "email":userObjData['email']})
            else:
                return JsonResponse({"success":False, "message":"Sorry, This is not a valid information, contact admin."})
        except exception as e:
            logger.error("Problem with Update User")
            return JsonResponse({"success": False, "message":str(e)})
        #return JsonResponse({"success":"true"})

def resetPwd(request, format=None):
    lookup_field = 'email'
    model = User
    if request.method == 'GET':
        return JsonResponse({'message' : 'Please use POST with applicable JSON for login service'})
    elif request.method == 'POST':
        userObjData = json.loads(request.body.decode('utf-8'))
        #print(userObjData)
        subscriberPwd = User.objects.get(email = userObjData['email'])
        userid = subscriberPwd.id
        mailinfo=[]
        def store3(userid):
            if subscriberPwd.is_active == 1:
                pwdMsg = 'Your Password Changed Successfully,LogIn with your credentials'
                userdet = User.objects.get(id=userid)
                subject = "Change Password"
                to_email = userdet.email
                ctx={
                    'first_name':userdet.first_name
                }
                message = render_to_string('changepassword.html',ctx)
                mailinfo.append(subject)
                mailinfo.append(message)
                mailinfo.append(to_email)
                mailinfo.append(pwdMsg)
                return mailinfo
            #officeMail(subject, message, to_email)
            #print('in changepassword temp')
            else:
                pwdMsg = 'Your Password Set Successfully,LogIn with your credentials'
                subdeatails = User.objects.get(id=userid)
                subject = "Welcome to StratFit"
                to_email = subdeatails.email
                ctx={
                    'first_name':subdeatails.first_name
                }
                message = render_to_string('welcome.html',ctx)
                mailinfo.append(subject)
                mailinfo.append(message)
                mailinfo.append(to_email)
                mailinfo.append(pwdMsg)
                return mailinfo
            #officeMail(subject, message, to_email)
            #print('in welcome temp')
        def mail3(info):
            subject=info[0]
            message=info[1]
            to_email=info[2]
            print("hherrefdvvvvvdghhhhbv")
            officeMail(subject, message, to_email)

        with concurrent.futures.ThreadPoolExecutor() as executor:
            future=executor.submit(store3,userid)
            info=future.result()
        t2=threading.Thread(target=mail3,args=(info,))
        t2.start()
        #t2.join()
        pwdMsg=info[3]
        subscriberExist = User.objects.filter(email=userObjData['email'])
        if(subscriberExist.exists()):
            instance = User.objects.get(email=userObjData['email'])
            instance.password = make_password(userObjData['password'])
            instance.is_active = 1
            instance.save()
            return JsonResponse({"success":True, "message":pwdMsg})
        else:
            return JsonResponse({"success":False, "message":"No Valid Email"})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def changePassword(request, format=None):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url = "http://alpha.stratfit.net/services/services/stratservices/subscriber/changePassword/"
    try:
        if username!=None:
            lookup_field = 'email'
            model = User
            if request.method == 'GET':
                return JsonResponse({'message' : 'Please use POST with applicable JSON for login service'})
            elif request.method == 'POST':
                userObjData = json.loads(request.body.decode('utf-8'))
                subscriberExist = User.objects.filter(id=userObjData['userId'])
                if(subscriberExist.exists()):
                    instance = User.objects.get(id=userObjData['userId'])
                    if check_password(userObjData['oldPassword'], instance.password):
                        instance.password = make_password(userObjData['newPassword'])
                        instance.save()
                        return JsonResponse({"success":True, "message":"Password has been changed successfully"})
                    else:
                        return JsonResponse({"success":False, "message":"Your old password is incorrect"})
                else:
                    return JsonResponse({"success":False, "message":"User not found"})
            else:
                return JsonResponse({'message': 'Please use POST with applicable JSON for login service'})
        else:
            return JsonResponse({"success":False, "message":"User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})
    
@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def ionicloginchecking(request):
    try:
        usertoken = json.loads(request.body.decode('utf-8'))
        stratsessionutil = StartFitSessionUtil()
        if request.META.get('HTTP_AUTHORIZATION') is not None:
            user = stratsessionutil.get_user_insession(request)
            uemail = user['email']
            queryset = User.objects.get(email= uemail)
            username = queryset.first_name
            fitProQuerySet = FitnessProfile.objects.select_related('User__id').filter(user_id=queryset.id).values('gender', 'dob', 'height', 'heightUnit','weight', 'weightUnit', 'user_id__id', 'user_id__email','user_id__first_name')
            isProfileSet = False
            dataGoalObj = {}
            dataFitObj = {}
            dataTmaxObj = {}
            if fitProQuerySet.exists():
                for dt in fitProQuerySet:
                    dataFitObj = dict(dt)
                    if dataFitObj['dob'] != None:
                        dataFitObj['dob1'] = dataFitObj['dob']
                        dataFitObj['dob'] = dataFitObj['dob'].strftime("%Y/%m/%d")
                        isProfileSet = True
            goalDetails = goals.objects.filter(user=queryset.id).values()
            isGoalSet = False
            if goalDetails.exists():
                isGoalSet = True
                for dt in goalDetails:
                    dataGoalObj = dict(dt)
            PlanDetails = UserPlan.objects.filter(user=queryset.id).filter(status__in=[1, 3]).values()
            isPlanSet = False
            isTmaxSet = False
            isFreeTrail = True
            plans = []
            tmaxArr = []
            orgValues = Organization.objects.get(id=queryset.organization_id)
            orgName = orgValues.gymName
            if PlanDetails.exists():
                isPlanSet = True
                isFreeTrail = False
                for dt in PlanDetails:
                    planObj = dict(dt)
                    planInfos = Plan.objects.select_related('Goals__id', 'ProgramType__id', 'User__id').filter(id=planObj['plan_id']).values('id', 'planName', 'planPhoto', 'createdBy__first_name','createdBy__last_name', 'price', 'duration_weeks', 'ability','planGoal__goalName', 'planDescription','programType__programTypeName','licencePolicy','createdBy_id','originalPlanner_id','iosPrice','iosStatus')
                    for dtp in planInfos:
                        planInfo = dict(dtp)
                        if planInfo['licencePolicy'] == "3" or planInfo['licencePolicy'] == "White-Label":
                            partnerName = User.objects.get(id=planInfo['createdBy_id'])
                            planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
                        else:
                            coachName = User.objects.get(id=planInfo['originalPlanner_id'])
                            planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
                        
                    planObj['info'] = planInfo
                    plans.append(planObj)
                tmaxDetails = UserTestPlan.objects.filter(user=queryset.id).values('createdDate', 'exerciseId_id','exerciseId_id__exerciseName','exerciseName', 'id', 'plan_id','tmax', 'updateTmax', 'updateType','updatedDate', 'user_id','userplan_id', 'workWeight', 'workoutTestDate')
                if tmaxDetails.exists():
                    isTmaxSet = True
                    for dt in tmaxDetails:
                        print(dt)
                        dataTmaxObj = dict(dt)
                        tmaxArr.append(dataTmaxObj)
            print(queryset.email)
            '''for userObj in user:
                uid = model_to_dict(userObj)
                print(uid)
            userRoleID = None'''
            if queryset.email is not None:
                request.session['loggedIn'] = True
                request.session['email'] = queryset.email
                request.session['user_id'] = queryset.id
                request.session['first_name'] = queryset.first_name
                request.session['is_superuser'] = queryset.is_superuser
                return JsonResponse({"success": True, "message": "Logged In successfully", "profile": dataFitObj, "goals": dataGoalObj,"tmax": tmaxArr, "plans": plans, "isProfileSet": isProfileSet, "isGoalSet": isGoalSet,"isPlanSet": isPlanSet, "isTmaxSet": isTmaxSet,"sessiontoken": usertoken['utokken'], "userDetails": uemail,"username": username, "fname": queryset.first_name, "lname": queryset.last_name,"is_superuser": queryset.is_superuser, "is_active": queryset.is_active,"user_id": queryset.id, "userType": queryset.userType,"orgId": queryset.organization_id, "avatar": queryset.avatar, "otp": queryset.otp,"phone":queryset.phone,"currencyType":queryset.currencyType,"orgName":orgName,"isFreeTrail":isFreeTrail,"email":queryset.email,"phonecode":queryset.phoneCode,"coverImage":queryset.userCover})
        else:
            return JsonResponse({"success": False, "message": "User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg":str(e)})


def userLogin(request):
    context = RequestContext(request)
    if request.method == 'POST':
        try:
            jsonD = json.loads(request.body.decode('utf-8'))
            jsonD['remote_ip'] = request.META.get('REMOTE_ADDR', None)
            currencyValues = PriceConversion.objects.get(id=1)
            inrValue = currencyValues.inrValue
            if 'email' in jsonD:
                print("CAME HERE")
                if 'skip' in jsonD and jsonD['skip'] == 1:
                    print("CAME HERE1")
                    updateuser = User.objects.get(email=jsonD['email'])
                    print("CAME HERE2")
                    updateuser.is_active = 1
                    updateuser.save()
                stratauthentication = StartFitAuthentication()
                loginResponse = stratauthentication.authenticate(jsonD)
                userDataObj = loginResponse
                #print(userDataObj)
                try:
                    if userDataObj['result'] == 'False':
                        #print(userDataObj['message'],"1244")
                        if 'is_active' in userDataObj:
                            return JsonResponse({"success":False, "is_active":0, "message":userDataObj['message']})
                        else:
                            return JsonResponse({"success":False,"message":userDataObj['message']})
                    else:
                        queryset = User.objects.get(email=userDataObj['userDetails']['email'])
                        username = queryset.first_name
                        if queryset.deviceType == '' or queryset.deviceType == None:
                            if 'deviceType' in jsonD and jsonD['deviceType'] != '':
                                queryset.deviceType = jsonD['deviceType']
                                queryset.save()
                        androidversion = AppVersion.objects.get(id=1)
                        iosversion = AppVersion.objects.get(id=2)
                        fitProQuerySet = FitnessProfile.objects.select_related('User__id').filter(user_id=queryset.id).values('gender','dob','height','heightUnit','weight','weightUnit','user_id__id', 'user_id__email', 'user_id__first_name','trainingLevel')
                        isProfileSet = False
                        dataGoalObj = {}
                        dataFitObj = {}
                        dataTmaxObj = {}
                        if fitProQuerySet.exists():
                            for dt in fitProQuerySet:
                                dataFitObj = dict(dt)
                                if dataFitObj['dob'] != None:
                                    isProfileSet = True
                                    dataFitObj['dob1'] = dataFitObj['dob']
                                    dataFitObj['dob'] = dataFitObj['dob']. strftime("%Y/%m/%d")
                        goalDetails = goals.objects.filter(user = queryset.id ).values()
                        isGoalSet = False
                        if goalDetails.exists():
                            isGoalSet = True
                            for dt in goalDetails:
                                print(dt)
                                dataGoalObj = dict(dt)
                                print(dataGoalObj)
                        PlanDetails = UserPlan.objects.filter(user = queryset.id).filter(status__in = [1,3]).values()
                        userCurrency = User.objects.get(id = queryset.id)
                        isPlanSet = False
                        isTmaxSet = False
                        plans = []
                        tmaxArr = []
                        isFreeTrail = True
                        if PlanDetails.exists():
                            isFreeTrail = False
                            isPlanSet = True
                            for dt in PlanDetails:
                                planObj = dict(dt)
                                downloadUsers = UserPlan.objects.filter(plan_id = planObj['plan_id']).count()
                                planInfos = Plan.objects.select_related('Goals__id','ProgramType__id','User__id').filter(id=planObj['plan_id']).values('id', 'planName', 'createdBy__first_name','createdBy__last_name', 'price', 'duration_weeks','ability', 'planGoal__goalName', 'planDescription','programType__programTypeName', 'planStatus','num_of_periods','num_of_sessions', 'goals','planPhoto', 'programType_id','createdBy__avatar','createdBy_id','originalPlanner_id','licencePolicy','iosPrice','iosStatus','indianIosPrice','indianPrice')
                                print(planInfos.query);
                                if planInfos.exists():
                                    for dtp in planInfos:
                                        planInfo = dict(dtp)
                                        planPurposesVal = PlanGoals.objects.select_related('PlanPurposes').filter(plan_id=planInfo['id']).values('planGoal_id__GoalName')
                                        purposes = ''
                                        for val in planPurposesVal:
                                            valObj = dict(val)
                                            purposes += ", " + valObj['planGoal_id__GoalName']
                                        if purposes != '':
                                            planGoals = purposes[1:]
                                        else:
                                            planGoals = ""
                                        planAbilityVal = SelectedAbilities.objects.select_related('PlanAbilities').filter(plan_id=planInfo['id']).values('ability_id__ability')
                                        abilitieslists = ''
                                        for val in planAbilityVal:
                                            valObj = dict(val)
                                            abilitieslists += ", " + valObj['ability_id__ability']
                                        if abilitieslists != '':
                                            planAbilities = abilitieslists[1:]
                                        else:
                                            planAbilities = ""
                                        planInfo['planPurpose'] = planAbilities
                                        planInfo['plan_goals'] = planGoals
                                        planInfo['ability'] = planAbilities
                                        planInfo['goals'] = planGoals
                                        if planInfo['licencePolicy'] == "3" or planInfo['licencePolicy'] == "White-Label":
                                            partnerName = User.objects.get(id=planInfo['createdBy_id'])
                                            planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
                                        else:
                                            coachName = User.objects.get(id=planInfo['originalPlanner_id'])
                                            planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
                                        
                                        planInfo['genWarmupVideo'] = 'ztxEOSIcMc4'
                                        planInfo['cooldownVideo'] = '2esZzqjO5Cc'
                                        planInfo['planUsers'] = downloadUsers
                                        print(userDataObj,"userDataOBJ")
                                        if 'deviceType' in jsonD and jsonD['deviceType'] =='ios':
                                            if userCurrency.currencyType == "INR":
                                                if userDataObj['userDetails']['userCountry'] == 88:
                                                    planInfo['price'] = planInfo['indianIosPrice']
                                                    planInfo['planPrice'] = planInfo['indianIosPrice']
                                                    planInfo['iosPrice'] = planInfo['indianIosPrice']
                                                else:
                                                    planInfo['price'] = planInfo['iosPrice']
                                                    planInfo['planPrice'] = planInfo['iosPrice']
                                                if int(planInfo['price']) == 0:
                                                    planInfo['price'] = "Free"
                                            else:
                                                if userDataObj['userDetails']['userCountry'] == 88:
                                                    usdValue = PriceMapping.objects.values().filter(inr=planInfo['indianIosPrice'])
                                                else:
                                                    usdValue = PriceMapping.objects.values().filter(inr=planInfo['iosPrice'])
                                                for usd in usdValue:
                                                    usdObj = dict(usd)
                                                    dollarVal = usdObj['usd']
                                                planInfo['price'] = dollarVal
                                                if userDataObj['userDetails']['userCountry'] == 88:
                                                    planInfo['iosPrice'] = planInfo['indianIosPrice']
                                                if int(planInfo['price']) == 0:
                                                    planInfo['price'] = "Free"
                                        else:
                                            if int(planInfo['price']) == 0:
                                                planInfo['price'] = "Free"
                                            else:
                                                if userCurrency.currencyType == "INR":
                                                    if userDataObj['userDetails']['userCountry'] == 88:
                                                        planInfo['price'] = (planInfo['indianPrice'])
                                                        planInfo['planPrice'] = planInfo['indianPrice']
                                                        planInfo['iosPrice'] = planInfo['indianIosPrice']
                                                    else:
                                                        planInfo['price'] = (planInfo['price'])
                                                        planInfo['planPrice'] = planInfo['price']
                                                else:
                                                    if userDataObj['userDetails']['userCountry'] == 88:
                                                        usdValue = PriceMapping.objects.get(inr=planInfo['indianIosPrice'])
                                                        planInfo['price'] = planInfo['indianPrice']
                                                        planInfo['planPrice'] = planInfo['indianPrice']
                                                        planInfo['iosPrice'] = usdValue.usd
                                                    else:
                                                        usdValue = PriceMapping.objects.get(inr=planInfo['iosPrice'])
                                                        planInfo['iosPrice'] = usdValue.usd
                                                        planInfo['price'] = planInfo['price']
                                                        planInfo['planPrice'] = planInfo['price']
                                                if float(planInfo['price']) == 0:
                                                    planInfo['price'] = "Free"
                                                    # planInfo['iosPrice'] = round(float(planInfo['iosPrice'])*float(inrValue))
                                    planObj['info'] = planInfo
                                    plans.append(planObj)
                            tmaxDetails = UserTestPlan.objects.filter(user = queryset.id ).values('createdDate', 'exerciseId_id', 'exerciseId_id__exerciseName', 'exerciseName', 'id', 'plan_id', 'tmax', 'updateTmax', 'updateType', 'updatedDate', 'user_id', 'userplan_id', 'workWeight', 'workoutTestDate')
                            if tmaxDetails.exists():
                                isTmaxSet = True
                                for dt in tmaxDetails:
                                    print(dt)
                                    dataTmaxObj = dict(dt)
                                    tmaxArr.append(dataTmaxObj)
                        print(queryset.email)
                        '''for userObj in user:
                            uid = model_to_dict(userObj)
                            print(uid)
                        userRoleID = None'''
                        orgValues = Organization.objects.get(id = queryset.organization_id)
                        orgName = orgValues.gymName
                        usersessions = UsersValidSessions.objects.filter(user_id=queryset.id).values()
                        if usersessions.exists():
                            for sess in usersessions:
                                sessObj = dict(sess)
                                sessKey = sessObj['sessionToken']
                                cache.delete(sessKey)
                                updatesession = UsersValidSessions.objects.get(id=sessObj['id'])
                                updatesession.sessionToken = loginResponse['sessiontoken']
                                updatesession.save()
                        else:
                            createUserSess = UsersValidSessions.objects.create(
                                user_id = queryset.id,
                                sessionToken = loginResponse['sessiontoken']
                            )
                            createUserSess.save()
                        x = connection.cursor()
                        allExecDetails = "SELECT *,uae.id AS advexId,ue.id as id,uv.videoLink as video_id__videoLink FROM `utility_exercise` ue LEFT JOIN `utility_advexercises` uae ON ue.id = uae.exercise_id LEFT JOIN `utility_videos` uv ON uv.id = ue.video_id WHERE ue.id IS NOT NULL AND ue.accessLevel = 0 AND ue.exerciseStatus =1 ORDER BY ue.exOrder ASC"
                        #print(allExecDetails)
                        x.execute(allExecDetails)
                        resultQuery = dictfetchall(x)
                        PlanExercises = []
                        for dt7 in resultQuery:
                            dataExObj = dict(dt7)
                            PlanExercises.append(dataExObj)
                        print(queryset.id)
                        defaultTmax = defaultTmaxValues(queryset.id, PlanExercises)
                        print("Here I AM")
                        if defaultTmax != []:
                            for ex1 in PlanExercises:
                                exId = ex1['id']
                                firstTemp = False
                                for dex in defaultTmax:
                                    if dex['exId'] == exId:
                                        ex1['defaultTmax'] = dex['tmaxVal']
                                        firstTemp = True
                                    elif firstTemp == False:
                                        ex1['defaultTmax'] = 0
                        if queryset.email is not None:
                            request.session['loggedIn'] = True
                            request.session['email'] = queryset.email
                            request.session['user_id'] = queryset.id
                            request.session['first_name'] = queryset.first_name
                            request.session['is_superuser'] = queryset.is_superuser
                            return JsonResponse({"Exercises":PlanExercises,"success":True,"message": "Logged In successfully", "profile":dataFitObj, "goals":dataGoalObj, "tmax":tmaxArr, "plans":plans, "isProfileSet":isProfileSet, "isGoalSet":isGoalSet, "isPlanSet":isPlanSet, "isTmaxSet":isTmaxSet,"code":loginResponse['code'],"sessiontoken":loginResponse['sessiontoken'],"userDetails":userDataObj['userDetails']['email'],"username":username,"fname":queryset.first_name,"privacy":queryset.userPrivacy,"lname":queryset.last_name,"is_superuser":queryset.is_superuser,"is_active":queryset.is_active,"user_id":userDataObj['userDetails']['id'],"userType":queryset.userType,"orgId":queryset.organization_id,"avatar":queryset.avatar,"otp":queryset.otp,"orgName":orgName,"isFreeTrail":isFreeTrail,"phone":userDataObj['userDetails']['phone'],"currencyType":userDataObj['userDetails']['currencyType'],"email":queryset.email,"phonecode":userDataObj['userDetails']['phoneCode'],"coverImage":userDataObj['userDetails']['userCover'],"androidVersion":androidversion.version,"iosVersion":iosversion.version,"generalWarmup":[{"Name":"Hip Circles","Reps":5,"ExTime":"Not Applicable","Direction":"Both","Equipment":"Not Applicable"},{"Name":"Knee Circles","Reps":10,"ExTime":"Not Applicable","Direction":"Both","Equipment":"Not Applicable"},{"Name":"Standing lower back release","Reps":10,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Not Applicable"},{"Name":"Roll overs","Reps":10,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Not Applicable"},{"Name":"Fire Hydrant Circles","Reps":10,"ExTime":"Not Applicable","Direction":"Each leg / Direction","Equipment":"Not Applicable"},{"Name":"Foam Rolling - Back","Reps":8,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Foam Roller"},{"Name":"IT Band","Reps":8,"ExTime":"Not Applicable","Direction":"Each leg","Equipment":"Foam Roller"},{"Name":"Adductors","Reps":8,"ExTime":"Not Applicable","Direction":"Each leg","Equipment":"Foam Roller"},{"Name":"Ball Rolling (Cricket / Baseball)","Reps":0,"ExTime":"30","Direction":"Each side","Equipment":"Cricket / Baseball"},{"Name":"Arm Swings - Over under","Reps":10,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Not Applicable"}], "Cooldown":[{"name":"FLoor Quadraceps Stretch"},{"name":"Floor Glute Stretch"},{"name":"Neck, Back, and Hamstring Stretch"},{"name":"Classic Hamstring Stretch"},{"name":"Shoulders and Biceps Stretch"},{"name":"Lower Back Stretch"},{"name":"Frog Stretch"},{"name":"Cat Stretch"},{"name":"Triceps and Lat Reach Stretch"}], "exerciseWarmup":{"strength":[{"Sets":1,"Reps":10,"intensity":50},{"Sets":1,"Reps":6,"intensity":60},{"Sets":1,"Reps":4,"intensity":70},{"Sets":1,"Reps":3,"intensity":80},{"Sets":1,"Reps":1,"intensity":90}],"explosive":[{"Sets":1,"Reps":5,"intensity":50},{"Sets":1,"Reps":5,"intensity":50},{"Sets":1,"Reps":3,"intensity":60},{"Sets":1,"Reps":3,"intensity":60},{"Sets":1,"Reps":3,"intensity":70},{"Sets":1,"Reps":1,"intensity":80},{"Sets":1,"Reps":1,"intensity":90}]}})
                except Exception as e:
                    return JsonResponse({"msg":str(e)})
                    JsonResponse("Login attempt failed with user", safe=False)
                    authResponse = AuthResponse()
                    authResponse.code = 401
                    authResponse.message = "Invalid_Credentials"
                    return JsonResponse({"success": False, "message": "Invalid Username Or Password"})
            else:
                sessionAuthentication = SessionAuthentication()
                username = sessionAuthentication.authenticate(request)
                if username is not None:
                    loginResponse = '{"result":"success"}'
                else:
                    loginResponse = '{"result":"failure"}'
                return Response(loginResponse)
        except Exception as e:
            # logger.exception("fatal error")
            return JsonResponse({"msg":str(e)})
            #return JsonResponse({"success": False, "message": "Your account is disabled"})

def userLoginNew(request):
    context = RequestContext(request)
    if request.method == 'POST':
        try:
            jsonD = json.loads(request.body.decode('utf-8'))
            jsonD['remote_ip'] = request.META.get('REMOTE_ADDR', None)
            currencyValues = PriceConversion.objects.get(id=1)
            inrValue = currencyValues.inrValue
            if 'email' in jsonD:
                print("CAME HERE")
                if 'skip' in jsonD and jsonD['skip'] == 1:
                    print("CAME HERE1")
                    updateuser = User.objects.get(email=jsonD['email'])
                    print("CAME HERE2")
                    updateuser.is_active = 1
                    updateuser.save()
                stratauthentication = StartFitAuthentication()
                print(stratauthentication,"hdddddddddddddddddddddddddddddddddddddddddddd")
                loginResponse = stratauthentication.authenticate(jsonD)
                print(loginResponse,"kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkiiiiiiiiiiiiiiiiiiiiiii")
                userDataObj = loginResponse
                #print(userDataObj)
                try:
                    if userDataObj['result'] == 'False':
                        #print(userDataObj['message'],"1244")
                        if 'is_active' in userDataObj:
                            return JsonResponse({"success":False, "is_active":0, "message":userDataObj['message']})
                        else:
                            return JsonResponse({"success":False,"message":userDataObj['message']})
                    else:
                        queryset = User.objects.get(email=userDataObj['userDetails']['email'])
                        username = queryset.first_name
                        if queryset.deviceType == '' or queryset.deviceType == None:
                            if 'deviceType' in jsonD and jsonD['deviceType'] != '':
                                queryset.deviceType = jsonD['deviceType']
                                queryset.save()
                        androidversion = AppVersion.objects.get(id=1)
                        iosversion = AppVersion.objects.get(id=2)
                        fitProQuerySet = FitnessProfile.objects.select_related('User__id').filter(user_id=queryset.id).values('gender','dob','height','heightUnit','weight','weightUnit','user_id__id', 'user_id__email', 'user_id__first_name','trainingLevel')
                        isProfileSet = False
                        dataGoalObj = {}
                        dataFitObj = {}
                        dataTmaxObj = {}
                        if fitProQuerySet.exists():
                            for dt in fitProQuerySet:
                                dataFitObj = dict(dt)
                                if dataFitObj['dob'] != None:
                                    isProfileSet = True
                                    dataFitObj['dob1'] = dataFitObj['dob']
                                    dataFitObj['dob'] = dataFitObj['dob']. strftime("%Y/%m/%d")
                        goalDetails = goals.objects.filter(user = queryset.id ).values()
                        isGoalSet = False
                        if goalDetails.exists():
                            isGoalSet = True
                            for dt in goalDetails:
                                print(dt)
                                dataGoalObj = dict(dt)
                                print(dataGoalObj)
                        PlanDetails = ProgramUserPlan.objects.filter(user = queryset.id).filter(status__in = [1,3]).values()
                        userCurrency = User.objects.get(id = queryset.id)
                        isPlanSet = False
                        isTmaxSet = False
                        plans = []
                        tmaxArr = []
                        isFreeTrail = True
                        if PlanDetails.exists():
                            isFreeTrail = False
                            isPlanSet = True
                            for dt in PlanDetails:
                                planObj = dict(dt)
                                downloadUsers = ProgramUserPlan.objects.filter(plan_id = planObj['plan_id']).count()
                                planInfos = ProgramPlan.objects.select_related('Goals__id','ProgramType__id','User__id').filter(id=planObj['plan_id']).values('id', 'planName', 'createdBy__first_name','createdBy__last_name', 'price', 'duration_weeks','ability', 'planGoal__goalName', 'planDescription','programType__programTypeName', 'planStatus','num_of_periods','num_of_sessions', 'goals','planPhoto', 'programType_id','createdBy__avatar','createdBy_id','originalPlanner_id','licencePolicy','iosPrice','iosStatus','indianIosPrice','indianPrice')
                                print(planInfos.query)
                                planInfo = {}
                                for dtp in planInfos:
                                    planInfo = dict(dtp)
                                    planPurposesVal = ProgramPlanGoals.objects.select_related('PlanPurposes').filter(plan_id=planInfo['id']).values('planGoal_id__GoalName')
                                    purposes = ''
                                    for val in planPurposesVal:
                                        valObj = dict(val)
                                        purposes += ", " + valObj['planGoal_id__GoalName']
                                    if purposes != '':
                                        planGoals = purposes[1:]
                                    else:
                                        planGoals = ""
                                    planAbilityVal = ProgramSelectedAbilities.objects.select_related('PlanAbilities').filter(plan_id=planInfo['id']).values('ability_id__ability')
                                    abilitieslists = ''
                                    for val in planAbilityVal:
                                        valObj = dict(val)
                                        abilitieslists += ", " + valObj['ability_id__ability']
                                    if abilitieslists != '':
                                        planAbilities = abilitieslists[1:]
                                    else:
                                        planAbilities = ""
                                    planInfo['planPurpose'] = planAbilities
                                    planInfo['plan_goals'] = planGoals
                                    planInfo['ability'] = planAbilities
                                    planInfo['goals'] = planGoals
                                    if planInfo['licencePolicy'] == "3" or planInfo['licencePolicy'] == "White-Label":
                                        partnerName = User.objects.get(id=planInfo['createdBy_id'])
                                        planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
                                    else:
                                        coachName = User.objects.get(id=planInfo['originalPlanner_id'])
                                        planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
                                    
                                    
                                    planInfo['genWarmupVideo'] = 'ztxEOSIcMc4'
                                    planInfo['cooldownVideo'] = '2esZzqjO5Cc'
                                    planInfo['planUsers'] = downloadUsers
                                    print(userDataObj,"userDataOBJ")
                                    if 'deviceType' in jsonD and jsonD['deviceType'] =='ios':
                                        if userCurrency.currencyType == "INR":
                                            if userDataObj['userDetails']['userCountry'] == 88:
                                                planInfo['price'] = planInfo['indianIosPrice']
                                                planInfo['planPrice'] = planInfo['indianIosPrice']
                                                planInfo['iosPrice'] = planInfo['indianIosPrice']
                                            else:
                                                planInfo['price'] = planInfo['iosPrice']
                                                planInfo['planPrice'] = planInfo['iosPrice']
                                            if int(planInfo['price']) == 0:
                                                planInfo['price'] = "Free"
                                        else:
                                            if userDataObj['userDetails']['userCountry'] == 88:
                                                usdValue = PriceMapping.objects.values().filter(inr=planInfo['indianIosPrice'])
                                            else:
                                                usdValue = PriceMapping.objects.values().filter(inr=planInfo['iosPrice'])
                                            for usd in usdValue:
                                                usdObj = dict(usd)
                                                dollarVal = usdObj['usd']
                                            planInfo['price'] = dollarVal
                                            if userDataObj['userDetails']['userCountry'] == 88:
                                                planInfo['iosPrice'] = planInfo['indianIosPrice']
                                            if int(planInfo['price']) == 0:
                                                planInfo['price'] = "Free"
                                    else:
                                        if int(planInfo['price']) == 0:
                                            planInfo['price'] = "Free"
                                        else:
                                            if userCurrency.currencyType == "INR":
                                                if userDataObj['userDetails']['userCountry'] == 88:
                                                    planInfo['price'] = (planInfo['indianPrice'])
                                                    planInfo['planPrice'] = planInfo['indianPrice']
                                                    planInfo['iosPrice'] = planInfo['indianIosPrice']
                                                else:
                                                    planInfo['price'] = (planInfo['price'])
                                                    planInfo['planPrice'] = planInfo['price']
                                            else:
                                                if userDataObj['userDetails']['userCountry'] == 88:
                                                    usdValue = PriceMapping.objects.get(inr=planInfo['indianIosPrice'])
                                                    planInfo['price'] = planInfo['indianPrice']
                                                    planInfo['planPrice'] = planInfo['indianPrice']
                                                    planInfo['iosPrice'] = usdValue.usd
                                                else:
                                                    usdValue = PriceMapping.objects.get(inr=planInfo['iosPrice'])
                                                    planInfo['iosPrice'] = usdValue.usd
                                                    planInfo['price'] = planInfo['price']
                                                    planInfo['planPrice'] = planInfo['price']
                                            if float(planInfo['price']) == 0:
                                                planInfo['price'] = "Free"
                                                # planInfo['iosPrice'] = round(float(planInfo['iosPrice'])*float(inrValue))
                                planObj['info'] = planInfo
                                plans.append(planObj)
                            '''
                            tmaxDetails = UserTestPlan.objects.filter(user = queryset.id ).values('createdDate', 'exerciseId_id', 'exerciseId_id__exerciseName', 'exerciseName', 'id', 'plan_id', 'tmax', 'updateTmax', 'updateType', 'updatedDate', 'user_id', 'userplan_id', 'workWeight', 'workoutTestDate')
                            if tmaxDetails.exists():
                                isTmaxSet = True
                                for dt in tmaxDetails:
                                    print(dt)
                                    dataTmaxObj = dict(dt)
                                    tmaxArr.append(dataTmaxObj)
                        print(queryset.email)
                        for userObj in user:
                            uid = model_to_dict(userObj)
                            print(uid)
                        userRoleID = None
                        '''
                        orgValues = Organization.objects.get(id = queryset.organization_id)
                        orgName = orgValues.gymName
                        usersessions = UsersValidSessions.objects.filter(user_id=queryset.id).values()
                        if usersessions.exists():
                            for sess in usersessions:
                                sessObj = dict(sess)
                                sessKey = sessObj['sessionToken']
                                cache.delete(sessKey)
                                updatesession = UsersValidSessions.objects.get(id=sessObj['id'])
                                updatesession.sessionToken = loginResponse['sessiontoken']
                                updatesession.save()
                        else:
                            createUserSess = UsersValidSessions.objects.create(
                                user_id = queryset.id,
                                sessionToken = loginResponse['sessiontoken']
                            )
                            createUserSess.save()
                        '''    
                        x = connection.cursor()
                        allExecDetails = "SELECT *,uae.id AS advexId,ue.id as id,uv.videoLink as video_id__videoLink FROM `utility_exercise` ue LEFT JOIN `utility_advexercises` uae ON ue.id = uae.exercise_id LEFT JOIN `utility_videos` uv ON uv.id = ue.video_id WHERE ue.id IS NOT NULL AND ue.accessLevel = 0 AND ue.exerciseStatus =1 ORDER BY ue.exOrder ASC"
                        #print(allExecDetails)
                        x.execute(allExecDetails)
                        resultQuery = dictfetchall(x)
                        PlanExercises = []
                        for dt7 in resultQuery:
                            dataExObj = dict(dt7)
                            PlanExercises.append(dataExObj)
                        print(queryset.id)
                        defaultTmax = defaultTmaxValues(queryset.id, PlanExercises)
                        print("Here I AM")
                        if defaultTmax != []:
                            for ex1 in PlanExercises:
                                exId = ex1['id']
                                firstTemp = False
                                for dex in defaultTmax:
                                    if dex['exId'] == exId:
                                        ex1['defaultTmax'] = dex['tmaxVal']
                                        firstTemp = True
                                    elif firstTemp == False:
                                        ex1['defaultTmax'] = 0
                        '''                
                        if queryset.email is not None:
                            request.session['loggedIn'] = True
                            request.session['email'] = queryset.email
                            request.session['user_id'] = queryset.id
                            request.session['first_name'] = queryset.first_name
                            request.session['is_superuser'] = queryset.is_superuser
                            return JsonResponse({"success":True,"message": "Logged In successfully", "profile":dataFitObj, "goals":dataGoalObj,  "plans":plans, "isProfileSet":isProfileSet, "isGoalSet":isGoalSet, "isPlanSet":isPlanSet, "isTmaxSet":isTmaxSet,"code":loginResponse['code'],"sessiontoken":loginResponse['sessiontoken'],"userDetails":userDataObj['userDetails']['email'],"username":username,"fname":queryset.first_name,"privacy":queryset.userPrivacy,"lname":queryset.last_name,"is_superuser":queryset.is_superuser,"is_active":queryset.is_active,"user_id":userDataObj['userDetails']['id'],"userType":queryset.userType,"orgId":queryset.organization_id,"avatar":queryset.avatar,"otp":queryset.otp,"orgName":orgName,"isFreeTrail":isFreeTrail,"phone":userDataObj['userDetails']['phone'],"currencyType":userDataObj['userDetails']['currencyType'],"email":queryset.email,"phonecode":userDataObj['userDetails']['phoneCode'],"coverImage":userDataObj['userDetails']['userCover'],"androidVersion":androidversion.version,"iosVersion":iosversion.version,"generalWarmup":[{"Name":"Hip Circles","Reps":5,"ExTime":"Not Applicable","Direction":"Both","Equipment":"Not Applicable"},{"Name":"Knee Circles","Reps":10,"ExTime":"Not Applicable","Direction":"Both","Equipment":"Not Applicable"},{"Name":"Standing lower back release","Reps":10,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Not Applicable"},{"Name":"Roll overs","Reps":10,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Not Applicable"},{"Name":"Fire Hydrant Circles","Reps":10,"ExTime":"Not Applicable","Direction":"Each leg / Direction","Equipment":"Not Applicable"},{"Name":"Foam Rolling - Back","Reps":8,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Foam Roller"},{"Name":"IT Band","Reps":8,"ExTime":"Not Applicable","Direction":"Each leg","Equipment":"Foam Roller"},{"Name":"Adductors","Reps":8,"ExTime":"Not Applicable","Direction":"Each leg","Equipment":"Foam Roller"},{"Name":"Ball Rolling (Cricket / Baseball)","Reps":0,"ExTime":"30","Direction":"Each side","Equipment":"Cricket / Baseball"},{"Name":"Arm Swings - Over under","Reps":10,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Not Applicable"}], "Cooldown":[{"name":"FLoor Quadraceps Stretch"},{"name":"Floor Glute Stretch"},{"name":"Neck, Back, and Hamstring Stretch"},{"name":"Classic Hamstring Stretch"},{"name":"Shoulders and Biceps Stretch"},{"name":"Lower Back Stretch"},{"name":"Frog Stretch"},{"name":"Cat Stretch"},{"name":"Triceps and Lat Reach Stretch"}]})
                except Exception as e:
                    return JsonResponse({"msg":str(e)})
                    JsonResponse("Login attempt failed with user", safe=False)
                    authResponse = AuthResponse()
                    authResponse.code = 401
                    authResponse.message = "Invalid_Credentials"
                    return JsonResponse({"success": False, "message": "Invalid Username Or Password"})
            else:
                sessionAuthentication = SessionAuthentication()
                username = sessionAuthentication.authenticate(request)
                if username is not None:
                    loginResponse = '{"result":"success"}'
                else:
                    loginResponse = '{"result":"failure"}'
                return Response(loginResponse)
        except Exception as e:
            # logger.exception("fatal error")
            return JsonResponse({"msg":str(e)})
            #return JsonResponse({"success": False, "message": "Your account is disabled"})

def userLoginByOTP(request):
    context = RequestContext(request)
    if request.method == 'POST':
        try:
            jsonD = json.loads(request.body.decode('utf-8'))
            jsonD['remote_ip'] = request.META.get('REMOTE_ADDR', None)
            currencyValues = PriceConversion.objects.get(id=1)
            inrValue = currencyValues.inrValue
            if 'email' in jsonD:
                loginSubs = User.objects.filter(email=jsonD['email'])
                print(loginSubs)
                if len(loginSubs) == 0:
                    print("12345")
                    resposeArr = {}
                    resposeArr['code'] = 200
                    resposeArr['result'] = 'False'
                    resposeArr['message'] = 'No Such Mail Id Found'
                    return resposeArr
                loginSubscriber = User.objects.get(email=jsonD['email'])
                print(loginSubscriber)
                instanceSub = User.objects.get(id=loginSubscriber.id)
                randomCode = ''.join(choice('0123456789') for i in range(4))
                rand=str(randomCode)
                randnum=rand
                instanceSub.otp = randnum
                instanceSub.save()
                #print(loginSubscriber.password)
                #print(make_password(request['password']))
                #print(loginSubscriber)
                #print(loginSubscriber.id)
                
                try:
                    if loginSubscriber is None:
                        return JsonResponse({"success":False,"message":"invalid credentials"})
                    else:
                        mailContent = "<p>Dear " + instanceSub.first_name + ",</p><br/> <p>The OTP is: " + instanceSub.otp + "</p>"
                        subject = "Welcome To StratFit"
                        #from_email = 'admin@stratfit.co'
                        to_email = instanceSub.email
                        #send_mail(subject, mailContent, settings.EMAIL_HOST_USER, [to_email])
                        officeMail(subject, mailContent, to_email)
                        return JsonResponse({"success":False, "is_active":0, "message":"OTP Sent"})
                except Exception as e:
                    return JsonResponse({"msg":str(e)})
                    JsonResponse("Login attempt failed with user", safe=False)
                    authResponse = AuthResponse()
                    authResponse.code = 401
                    authResponse.message = "Invalid_Credentials"
                    return JsonResponse({"success": False, "message": "Invalid Username Or Password"})
            else:
                sessionAuthentication = SessionAuthentication()
                username = sessionAuthentication.authenticate(request)
                if username is not None:
                    loginResponse = '{"result":"success"}'
                else:
                    loginResponse = '{"result":"failure"}'
                return Response(loginResponse)
        except Exception as e:
            # logger.exception("fatal error")
            return JsonResponse({"msg":str(e)})
            #return JsonResponse({"success": False, "message": "Your account is disabled"})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def logOut(request):
    user = request.session.get('user_id', None)
    request.session.flush()
    auth = request.META.get('HTTP_AUTHORIZATION').split()
    #username = None
    #auth = request.META.get('HTTP_AUTHORIZATION').split()
    key = auth[0]
    cache.delete(key)
    request.session.modified = True
    #print(request.token,"here IAm")
    #request.token.delete()
    logout(request)
    return JsonResponse({"success":True})


@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def editProfile(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req="GET"
    url="subscriber/editprofile/"
    try:
        if username!=None:
            if request.session.__contains__('user_id'):
                user = username['id']
            try:
                UA = UserAddress.objects.values('id').filter(user_id=user)
                dataCount=''
                for dt in UA:
                    dataCount = dict(dt)
                if 'id' in dataCount:
                    userDetails = UserAddress.objects.select_related('User__id').values('user__first_name','user__email','user__middle_name','user__phone','user__phoneCode','user__qualification','user__reference','user__last_name','address1','address2','town','city','state','country','zipCode','timeZone','user__avatar','user__currencyType','user__userCover').filter(user_id = user)
                else:
                    userDetails = User.objects.values('first_name','last_name','email','id','phone','avatar','currencyType','userCover').filter(pk=user)
                for dt in userDetails:
                    dataObj = dict(dt)
                    trainerInf = trainerProfile.objects.filter(user_id = user).values()
                    for tr in trainerInf:
                        trObj = dict(tr)
                        dataObj['about'] = trObj['aboutTrainer']
                socialprfinfo = SocialProfile.objects.select_related('User__id').values('id','user_id','socailName','socialUrl').filter(user_id = user)
                socialArr =[]
                for dt1 in socialprfinfo:
                    socialObj = dict(dt1)
                    socialArr.append(socialObj)
                return JsonResponse({"data":dataObj,"socialdata":socialArr})
            except Exception as e:
                return JsonResponse({"success":False,"message":str(e)})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def profileSettings(request):
    #print(request.body)
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user=username['id']
    userInfo = json.loads(request.body.decode('utf-8'))
    req=userInfo
    url="subscriber/profile/"
    try:
        if username!=None:
            #print(userInfo)
            userInformation = User.objects.get(id = userInfo['id'])
            if 'currency' in userInfo['userInf']:
                userInformation.currencyType = userInfo['userInf']['currency']
            userInformation.first_name = userInfo['userInf']['first_name']
            if 'middle_name' in userInfo['userInf']:
                userInformation.middle_name = userInfo['userInf']['middle_name']
            userInformation.last_name = userInfo['userInf']['last_name']
            userInformation.phone = userInfo['userInf']['phone']
            userInformation.phoneCode=userInfo['userInf']['code']
            if 'pword' in userInfo['userInf'] and userInfo['userInf']['pword'] !='' and userInfo['userInf']['pword'] !=None:
                userInformation.password = make_password(userInfo['userInf']['pword'])
            if 'qualification' in userInfo['userInf'] and userInfo['userInf']['qualification'] !='' and userInfo['userInf']['qualification'] !=None:
                userInformation.qualification = userInfo['userInf']['qualification']
            if 'reference' in userInfo['userInf'] and userInfo['userInf']['reference'] !='' and userInfo['userInf']['reference'] !=None:
                userInformation.reference = userInfo['userInf']['reference']
            userInformation.save()
            userDetails = User.objects.filter(id = userInformation.id).values('first_name','last_name')

            if 'about' in userInfo['userInf']:
                trainerDetails = trainerProfile.objects.filter(user_id = userInfo['id']).values()
                if trainerDetails.exists():
                    for tr in trainerDetails:
                        trObj = dict(tr)
                        updateTrainer = trainerProfile.objects.get(id=trObj['id'])
                        updateTrainer.aboutTrainer =  userInfo['userInf']['about']
                        updateTrainer.save()
                else:
                    trainerValues = trainerProfile.objects.create(
                        user_id = userInfo['id'],
                        aboutTrainer =  userInfo['userInf']['about']
                    )
                    trainerValues.save()

            for val in userDetails:
                values = dict(val)
            useraddressExist = UserAddress.objects.filter(user_id=userInfo['id'])
            if(useraddressExist.exists()):
                userAdressInformatioin = UserAddress.objects.get(user_id = userInfo['id'])
                if 'address1' in userInfo['userInf'] and userInfo['userInf']['address1'] !='' and userInfo['userInf']['address1'] !=None:
                    userAdressInformatioin.address1 = userInfo['userInf']['address1']
                if 'address2' in userInfo['userInf'] and userInfo['userInf']['address2'] !='' and userInfo['userInf']['address2'] !=None:
                    userAdressInformatioin.address2 = userInfo['userInf']['address2']
                if 'town' in userInfo['userInf'] and userInfo['userInf']['town'] !='' and userInfo['userInf']['town'] !=None:
                    userAdressInformatioin.town = userInfo['userInf']['town']
                if 'city' in userInfo['userInf'] and userInfo['userInf']['city'] !='' and userInfo['userInf']['city'] !=None:
                    userAdressInformatioin.city = userInfo['userInf']['city']
                if 'state' in userInfo['userInf'] and userInfo['userInf']['state'] !='' and userInfo['userInf']['state'] !=None:
                    userAdressInformatioin.state = userInfo['userInf']['state']
                if 'country' in userInfo['userInf'] and userInfo['userInf']['country'] !='' and userInfo['userInf']['country'] !=None:
                    userAdressInformatioin.country = userInfo['userInf']['country']
                if 'zipCode' in userInfo['userInf'] and userInfo['userInf']['zipCode'] !='' and userInfo['userInf']['zipCode'] !=None:
                    userAdressInformatioin.zipCode = userInfo['userInf']['zipCode']
                if 'timeZone' in userInfo['userInf'] and userInfo['userInf']['timeZone'] !='' and userInfo['userInf']['timeZone'] !=None:
                    userAdressInformatioin.timeZone = userInfo['userInf']['timeZone']
                userAdressInformatioin.save()
                return JsonResponse({"success": True, "message": " User Information Saved Successfully ","details":values})
            else:
                userAdressInformatioin = UserAddress.objects.create(
                    user_id = userInformation.id
                )
                if 'town' in userInfo['userInf'] and userInfo['userInf']['town']!='':
                    userAdressInformatioin.town =userInfo['userInf']['town']
                if 'city' in userInfo['userInf'] and userInfo['userInf']['city']!='':
                    userAdressInformatioin.city =userInfo['userInf']['city']
                if 'state' in userInfo['userInf'] and userInfo['userInf']['state']!='':
                    userAdressInformatioin.state =userInfo['userInf']['state']
                if 'country' in userInfo['userInf'] and userInfo['userInf']['country']!='':
                    userAdressInformatioin.country =userInfo['userInf']['country']
                if 'zipCode' in userInfo['userInf'] and userInfo['userInf']['zipCode']!='':
                    userAdressInformatioin.zipCode =userInfo['userInf']['zipCode']
                if 'address1' in userInfo['userInf'] and userInfo['userInf']['address1']!='':
                    userAdressInformatioin.address1 =userInfo['userInf']['address1']   
                if 'address2' in userInfo['userInf'] and userInfo['userInf']['address2']!='':
                    userAdressInformatioin.address2 =userInfo['userInf']['address2']
                if 'timeZone' in userInfo['userInf'] and userInfo['userInf']['timeZone']!=''  and userInfo['userInf']['timeZone']!=None:
                    userAdressInformatioin.timeZone = userInfo['userInf']['timeZone']
                userAdressInformatioin.save()
                return JsonResponse({"success": True, "message": " User Information Saved Successfully "})
        else:
            return JsonResponse({"success": False, "message": " User logged out "})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def socialmediainfo(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    userid = username['id']
    user=userid
    socInfo = json.loads(request.body.decode('utf-8'))
    req=socInfo
    url="subscriber/socialmediainfo/"
    try:
        print(userid,'---login userid----')
        if username!=None:
            print(socInfo,"1234567")
            rangeData = len(socInfo['socialinf'])
            for i in range(rangeData):
                if 'id' in socInfo['socialinf'][i]:
                    id = socInfo['socialinf'][i]['id']
                    socialtype = socInfo['socialinf'][i]['socailName']
                    if 'http://' in  socInfo['socialinf'][i]['socialUrl']:
                        socialUrl = socInfo['socialinf'][i]['socialUrl']
                    else:
                        socialUrl = "http://"+socInfo['socialinf'][i]['socialUrl']
                    dupsocailinf = SocialProfile.objects.get(pk =id)
                    dupsocailinf.socailName = socialtype
                    dupsocailinf.socialUrl = socialUrl
                    dupsocailinf.save()
                elif 'id' not in socInfo['socialinf'][i]:
                    socialtype = socInfo['socialinf'][i]['socailName']
                    if 'http' in  socInfo['socialinf'][i]['socialUrl']:
                        socialurl = socInfo['socialinf'][i]['socialUrl']
                    else:
                        socialurl = "http://"+socInfo['socialinf'][i]['socialUrl']
                    #socialurl = socInfo['socialinf'][i]['socialUrl']
                    socailinf = SocialProfile(
                        user_id = userid
                    )
                    socailinf.socailName = socialtype
                    socailinf.socialUrl = socialurl
                    socailinf.save()
            return JsonResponse({"success": True, "message": "User Social Information Saved Successfully "})
        else:
            return JsonResponse({"success":False,"message": "user logged out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})


@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def uploadphoto(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    data = json.loads(request.body.decode('utf-8'))
    req = data
    url = "subscriber/socialmediainfo/"
    try:
        if username != None:
            print("in Here")
            picUpload = User.objects.get(id = user)
            orgId =  picUpload.organization_id
            if 'gym' in data and data['gym'] == True:
                orgUpdate = Organization.objects.get(pk = orgId)
                if 'image' in data and data['image'] != '':
                    orgUpdate.logo = data['image']
                if 'cover' in data and data['cover'] != '':
                    orgUpdate.coverImage = data['cover']
                orgUpdate.save()
                return JsonResponse({"success": True, "message": "Image Uploaded Successfully", "avatar": orgUpdate.logo,"cover": orgUpdate.coverImage})
            else:
                if 'image' in data and data['image'] !='':
                    picUpload.avatar = data['image']
                if 'cover' in data and data['cover'] !='':
                    picUpload.userCover =  data['cover']
                picUpload.save()
                return JsonResponse({"success":True,"message":"Image Uploaded Successfully","avatar":picUpload.avatar,"cover":picUpload.userCover})
        else:
            return JsonResponse({"success":False,"message": "user logged out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def profilecheck(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user=username['id']
    user_data = json.loads(request.body.decode('utf-8'))
    req=user_data
    url="subscriber/profilecheck/"
    try:
        if username!=None:
            useraddressExist = FitnessProfile.objects.filter(user_id=user_data['id'])
            #print(useraddressExist.exists())
            if(useraddressExist.exists()):
                #print("exists")
                return JsonResponse({"success": True, "message": " User Already Exist "})
            else:
                #print("new")
                return JsonResponse({"success": False, "message": "New User"})
        else:
            return JsonResponse({"success": False, "message": "User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})


def forgotPassword(request):
    userObjData = json.loads(request.body.decode('utf-8'))
    req=userObjData
    url="subscriber/forgotPwd"
    #print(userObjData)
    userinf = User.objects.filter(email=userObjData['email'])
    try:
        rand=[]
        if (userinf.exists()):
            def storedata(userObjData):
                instanceSub = User.objects.get(email=userObjData['email'])
                randomCode = ''.join(choice('0123456789') for i in range(4))
                rand.append(instanceSub)
                rand.append(randomCode)
                print("hi")
                return rand
           
            def maildata(rand):
                instanceSub=rand[0]
                randomCode=rand[1]
                secret_code_plain = instanceSub.email + '#' + str(randomCode)
                secret_code_encode = base64.b64encode(secret_code_plain.encode('ascii'))
                #print(secret_code_encode)
                validateLink = request.META['HTTP_HOST']
                link = "http://"+validateLink+"/#/accountvalidate/" + secret_code_encode.decode("utf-8")
                #mailContent = "<p>Dear " + instanceSub.first_name+ ",</p><br/> <p>Please click here to change your password</p> <br /><p><a href='" + link + "' target='_blank' >" + link + "</a></p><p>or</p><p>The OTP is: " + str(randomCode)
                subject = "Password Recovery"
                to_email = instanceSub.email
                ctx={
                    'first_name':instanceSub.first_name,
                    'link':link,
                    'rand':str(randomCode)
                }
                message = render_to_string('forgot.html',ctx)
                officeMail(subject, message, to_email)
                '''msg = EmailMultiAlternatives(subject, message, from_email, [to_email])
                msg.attach_alternative(message, "text/html")
                msg.send()'''
                instanceSub.secretCode = secret_code_encode
                instanceSub.otp = str(randomCode)
                instanceSub.save()
                print("hihe")
                return randomCode
            with concurrent.futures.ThreadPoolExecutor() as executor:
                future=executor.submit(storedata,userObjData)
                rand=future.result() 
            t2=threading.Thread(target=maildata,args=(rand,))
            t2.start()
            #t2.join()

            return JsonResponse({"success": True, "message": "Please Check Your E-Mail to Reset Password"})
        else:
            return JsonResponse({"success": False, "message": "Email not registered, please register"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg":str(e)})


def resendOTP(request):
    userObjData = json.loads(request.body.decode('utf-8'))
    #print(userObjData)
    instanceSub = User.objects.get(email=userObjData['email'])
    createdTime = instanceSub.updatedDate
    print(createdTime)
    print(timezone.now() - timedelta(seconds=120))
    if createdTime > (timezone.now() - timedelta(seconds=120)):
        return JsonResponse({"message":"please wait for 2 minutes"})
    else:
        mailContent = "<p>Dear " + instanceSub.first_name + ",</p><br/> <p>The OTP is: " + instanceSub.otp + "</p>"
        subject = "Welcome To StratFit"
        #from_email = 'admin@stratfit.co'
        to_email = instanceSub.email
        #send_mail(subject, mailContent, settings.EMAIL_HOST_USER, [to_email])
        officeMail(subject, mailContent, to_email)
        '''msg = EmailMultiAlternatives(subject, mailContent, from_email, [to_email])
        msg.attach_alternative(mailContent, "text/html")
        msg.send()'''
        return JsonResponse({"success": True, "message": "Please Check Your E-Mail to Reset Password"})


def resendOTP1(request):
    userObjData = json.loads(request.body.decode('utf-8'))
    instanceSub = User.objects.get(email=userObjData['email'])   
    
    createdTime = instanceSub.updatedDate
    print(createdTime)
    print(timezone.now() - timedelta(seconds=120))
    try:    
        if createdTime > (timezone.now() - timedelta(seconds=120)):
            return JsonResponse({"message":"Please wait for 2 minutes"})
        else:
            def mail(instanceSub):
                mailContent = "<p>Dear " + instanceSub.first_name + ",</p><br/> <p>The OTP is: " + instanceSub.otp + "</p>"
                subject = "Welcome To StratFit"
                #from_email = 'admin@stratfit.co'
                to_email = instanceSub.email
                #send_mail(subject, mailContent, settings.EMAIL_HOST_USER, [to_email])
                officeMail(subject, mailContent, to_email)
                '''msg = EmailMultiAlternatives(subject, mailContent, from_email, [to_email])
                msg.attach_alternative(mailContent, "text/html")
                msg.send()'''
                return instanceSub.otp
            def response(instanceSub):
                if instanceSub.email:
                    return instanceSub.otp
            with concurrent.futures.ThreadPoolExecutor() as executor:
                future=executor.submit(response,instanceSub)
                rand=future.result() 
            t1=threading.Thread(target=mail,args=(instanceSub,)) 
            t1.start()          
            return JsonResponse({"success": True, "message": "One Time Passcode has been sent to your Email"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg":str(e)})
    
            
@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def userDetails(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url="subscriber/userDetails/"
    try:
        if username!=None:
            pInfo = json.loads(request.body.decode('utf-8'))
            if 'rows' in pInfo and pInfo['rows'] != '' and 'page' in pInfo and pInfo['page'] != '':
                rows = int(pInfo['rows'])
                print(rows)
                page = int(pInfo['page'])
                print(page)
                offset = (page - 1) * rows
                tot = page * rows
            else:
                food = User.objects.all()
            
                tot = food
            x = connection.cursor()
            users = "SELECT *,Subscriber_user.id as id FROM `Subscriber_user` left join Subscriber_useraddress on Subscriber_user.id = Subscriber_useraddress.user_id left join StratFitOrganization_organization on Subscriber_user.organization_id = StratFitOrganization_organization.id ORDER BY Subscriber_user.id DESC"
            x.execute(users)
            resultQuery = dictfetchall(x)
            #print(resultQuery)
            total = len(resultQuery)
            data = resultQuery[offset:tot]
            #print(total,"---------------",data,"-----------")
            dataArr = list()
            for dt in data:
                dataObj = dict(dt)
                if dataObj['date_joined'] != None:
                    dataObj['date_joined'] = dataObj['date_joined']. strftime("%d/%m/%Y %H:%M:%S")
                if dataObj['updatedDate'] != None:
                    dataObj['updatedDate'] = dataObj['updatedDate']. strftime("%d/%m/%Y %H:%M:%S")
                if dataObj['createdDate'] != None:
                    dataObj['createdDate'] = dataObj['createdDate']. strftime("%d/%m/%Y %H:%M:%S")
                if dataObj['last_login'] != None:
                    dataObj['last_login'] = dataObj['last_login']. strftime("%d/%m/%Y %H:%M:%S")
                if dataObj['modifiedDate'] != None:
                    dataObj['modifiedDate'] = dataObj['modifiedDate']. strftime("%d/%m/%Y %H:%M:%S")
                dataArr.append(dataObj)
            return JsonResponse({"rows":dataArr,"total":total})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def userSearch(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    searchData = json.loads(request.body.decode('utf-8'))
    req = searchData
    url = "subscriber/search/"
    try:
        if username!=None:
            searchData = json.loads(request.body.decode('utf-8'))
            print(searchData)
            if 'rows' in searchData and 'rows' != '':
                rows = int(searchData['rows'])
            else:
                rows = PAGING_ROWS

            if 'page' in searchData and 'page' != '':
                page = int(searchData['page'])
            else:
                page = 1

            offset = (page - 1) * rows
            tot = page * rows
            x = connection.cursor()
            fields = False
            if 'data' in searchData !='':
                users = "SELECT *,Subscriber_user.id as id FROM `Subscriber_user` left join StratFitOrganization_organization on Subscriber_user.organization_id = StratFitOrganization_organization.id left join Subscriber_useraddress on Subscriber_user.id = Subscriber_useraddress.user_id "
                #print(searchData['data'],"12345")
                if 'fname' in searchData['data'] and  searchData['data']['fname'] !='' or 'lname' in searchData['data'] and searchData['data']['lname'] != '' or 'email' in searchData['data'] and searchData['data']['email'] != '' or 'phone' in searchData['data']  and searchData['data']['phone'] !='' or 'gymName' in searchData['data']  and searchData['data']['gymName'] !='' or 'is_active' in searchData['data'] and searchData['data']['is_active'] !='':
                    users+=' where '
                    fields = True
                if 'fname' in searchData['data'] and searchData['data']['fname'] !='':
                    users += " first_name like'%"+str(searchData['data']['fname'])+ "%' AND"
                if 'lname' in searchData['data'] and searchData['data']['lname'] !='':
                    users += " last_name like '%"+str(searchData['data']['lname'])+ "%' AND"
                if 'email' in searchData['data'] and searchData['data']['email'] !='':
                    users += " email like'%"+str(searchData['data']['email'])+ "%' AND"
                if 'phone' in searchData['data'] and searchData['data']['phone'] !='':
                    users += " phone like'%"+str(searchData['data']['phone'])+ "%' AND"
                if 'gymName' in searchData['data'] and searchData['data']['gymName'] !='':
                    users += " gymName like'%"+str(searchData['data']['gymName'])+ "%' AND"
                if 'is_active' in searchData['data'] and searchData['data']['is_active'] !='':
                    print(searchData['data']['is_active'],"1234566")
                    users += " is_active ='"+searchData['data']['is_active']+ "' AND"
            #print(users[:-4])
            else:
                users = "SELECT *,Subscriber_user.id as id FROM `Subscriber_user` left join StratFitOrganization_organization on Subscriber_user.organization_id = StratFitOrganization_organization.id left join Subscriber_useraddress on Subscriber_user.id = Subscriber_useraddress.user_id"
            if(fields):
                users = users[:-4]
            searchQuery = users+" ORDER BY Subscriber_user.id DESC"
            print(searchQuery)
            x.execute(searchQuery)
            resultQuery = dictfetchall(x)
            #print(resultQuery)
            total = len(resultQuery)
            data = resultQuery[offset:tot]
            dataArr = list()
            for dt in data:
                dataObj = dict(dt)
                dataObj['fname'] = dataObj['first_name']
                dataObj['lname'] = dataObj['last_name']
                if dataObj['date_joined'] != None:
                    dataObj['date_joined'] = dataObj['date_joined']. strftime("%d/%m/%Y %H:%M:%S")
                if dataObj['updatedDate'] != None:
                    dataObj['updatedDate'] = dataObj['updatedDate']. strftime("%d/%m/%Y %H:%M:%S")
                if dataObj['createdDate'] != None:
                    dataObj['createdDate'] = dataObj['createdDate']. strftime("%d/%m/%Y %H:%M:%S")
                if dataObj['last_login'] != None:
                    dataObj['last_login'] = dataObj['last_login']. strftime("%d/%m/%Y %H:%M:%S")
                if dataObj['modifiedDate'] != None:
                    dataObj['modifiedDate'] = dataObj['modifiedDate']. strftime("%d/%m/%Y %H:%M:%S")
                dataArr.append(dataObj)
            return JsonResponse({"rows":dataArr,"total":total})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def galleryupload(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req="GET"
    url="subscriber/galleryupload"
    try:
        if username != None:
            files = request.FILES.getlist('uploadedFile')
            user = request.session['user_id']
            userphoto = UserPhoto.objects.create(
                user_id = user
            )
            for file in files:
                #print(file)
                #userphoto.photoname = 'test'
                userphoto.photo=file
                userphoto.save()
            return JsonResponse({"success":True})
        else:
            return JsonResponse({"success":False,"message":"User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def adminPanel(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    userInfo = json.loads(request.body.decode('utf-8'))
    req = userInfo
    url = "subscriber/adminPanel/"
    try:
        if username!=None:
            if 'id' in userInfo:
                print("--------------Update USer------------------")
                userInformation = User.objects.get(pk = userInfo['id'])
                userInformation.modifiedBy_id = user
                userInformation.first_name = userInfo['first_name']
                if 'middle_name' in userInfo and userInfo['middle_name'] !='' and userInfo['middle_name'] !=None:
                    userInformation.middle_name = userInfo['middle_name']
                if 'email' in userInfo and userInfo['email'] !='' and userInfo['email'] !=None:
                    userInformation.email = userInfo['email']
                if 'userType' in userInfo and userInfo['userType'] !='' and userInfo['userType'] !=None:
                    userInformation.userType = userInfo['userType']
                if 'is_active' in userInfo and userInfo['is_active'] !='' and userInfo['is_active'] !=None:
                    userInformation.is_active = userInfo['is_active']
                userInformation.last_name = userInfo['last_name']
                if 'pword' in userInfo and userInfo['pword'] !='' and userInfo['pword'] !=None:
                    userInformation.password = make_password(userInfo['pword'])
                userInformation.is_active = userInfo['is_active']
                if 'phone' in userInfo and userInfo['phone']!='' and userInfo['phone']!=None:

                    userInformation.phone = userInfo['phone']
                if 'phoneCode' in userInfo and userInfo['phoneCode']!='' and userInfo['phoneCode']!=None:

                    userInformation.phoneCode = userInfo['phoneCode']
                if 'qualification' in userInfo and userInfo['qualification'] !='' and userInfo['qualification'] !=None:
                    userInformation.qualification = userInfo['qualification']
                if 'reference' in userInfo and userInfo['reference'] !='' and userInfo['reference'] !=None:
                    userInformation.reference = userInfo['reference']
                if 'orgId' in userInfo and userInfo['orgId'] !='' and userInfo['orgId'] !=None:
                    userInformation.organization_id = userInfo['orgId']
                userInformation.save()
                if 'id' in userInfo and userInfo['user_id'] != None and userInfo['user_id'] !='':
                    userAdressInformatioin = UserAddress.objects.get(user_id = userInfo['user_id'])
                    if 'address1' in userInfo and userInfo['address1'] !='' and userInfo['address1'] !=None:
                        userAdressInformatioin.address1 = userInfo['address1']
                    if 'address2' in userInfo and userInfo['address2'] !='' and userInfo['address2'] !=None:
                        userAdressInformatioin.address2 = userInfo['address2']
                    if 'town' in userInfo and userInfo['town'] !='' and userInfo['town'] !=None:
                        userAdressInformatioin.town = userInfo['town']
                    if 'city' in userInfo and userInfo['city'] !='' and userInfo['city'] !=None:
                        userAdressInformatioin.city = userInfo['city']
                    if 'state' in userInfo and userInfo['state'] !='' and userInfo['state'] !=None:
                        userAdressInformatioin.state = userInfo['state']
                    if 'country' in userInfo and userInfo['country'] !='' and userInfo['country'] !=None:
                        userAdressInformatioin.country = userInfo['country']
                    if 'zipCode' in userInfo and userInfo['zipCode'] !='' and userInfo['zipCode'] !=None:
                        userAdressInformatioin.zipCode = userInfo['zipCode']
                    if 'timeZone' in userInfo and userInfo['timeZone'] !='' and userInfo['timeZone'] !=None:
                        userAdressInformatioin.timeZone = userInfo['timeZone']
                    userAdressInformatioin.save()
                else:
                    userAdressInformatioin = UserAddress.objects.create(
                        user_id = userInfo['id']
                    )
                    #userAdressInformatioin.user_id = userInformation.id
                    if 'address1' in userInfo and userInfo['address1'] !='' and userInfo['address1'] !=None:
                        userAdressInformatioin.address1 = userInfo['address1']
                    if 'address2' in userInfo and userInfo['address2'] !='' and userInfo['address2'] !=None:
                        userAdressInformatioin.address2 = userInfo['address2']
                    if 'town' in userInfo and userInfo['town'] !='' and userInfo['town'] !=None:
                        userAdressInformatioin.town = userInfo['town']
                    if 'city' in userInfo and userInfo['city'] !='' and userInfo['city'] !=None:
                        userAdressInformatioin.city = userInfo['city']
                    if 'state' in userInfo and userInfo['state'] !='' and userInfo['state'] !=None:
                        userAdressInformatioin.state = userInfo['state']
                    if 'country' in userInfo and userInfo['country'] !='' and userInfo['country'] !=None:
                        userAdressInformatioin.country = userInfo['country']
                    if 'zipCode' in userInfo and userInfo['zipCode'] !='' and userInfo['zipCode'] !=None:
                        userAdressInformatioin.zipCode = userInfo['zipCode']
                    if 'timeZone' in userInfo and userInfo['timeZone'] !='' and userInfo['timeZone'] !=None:
                        userAdressInformatioin.timeZone = userInfo['timeZone']
                    userAdressInformatioin.save()
                return JsonResponse({"success": True, "message": " User Updated successfully "})
            else:
                print("--------------Create USer------------------")
                try:
                    existingUser = User.objects.filter(email = userInfo['email'])
                    if existingUser.exists():
                        return JsonResponse({"success": False, "message": "User with that email already exists"})
                    else:
                        userInformation = User.objects.create(
                            createdBy_id=user,
                            modifiedBy_id=user,
                            email=userInfo['email'],
                            userType=userInfo['userType'],
                            organization_id=userInfo['orgId'],
                            is_active = userInfo['is_active']
                            
                        )
                        userInformation.save()
                        userInformation.first_name = userInfo['first_name']
                        if 'middle_name' in userInfo and userInfo['middle_name'] != '' and userInfo['middle_name'] != None:
                            userInformation.middle_name = userInfo['middle_name']
                        if 'last_name' in userInfo and userInfo['last_name'] != '' and userInfo['last_name'] != None:
                            userInformation.last_name = userInfo['last_name']
                        userInformation.email = userInfo['email']
                        userInformation.username = userInfo['email']
                        userInformation.password = make_password(userInfo['pword'])
                        userInformation.is_active = 1
                        if 'phone' in userInfo and userInfo['phone'] != '' and userInfo['phone'] != None:
                            userInformation.phone = userInfo['phone']
                        if 'qualification' in userInfo and userInfo['qualification'] != '' and userInfo['qualification'] != None:
                            userInformation.qualification = userInfo['qualification']
                        if 'reference' in userInfo and userInfo['reference'] != '' and userInfo['reference'] != None:
                            userInformation.reference = userInfo['reference']
                        # userInformation.affiliator = request.POST['affiliator']
                        # userInformation.fitnessUserAgentShare = request.POST['fitnessUserAgentShare']
                        # userInformation.trainerAgentShare = request.POST['trainerAgentShare']
                        # userInformation.gymAgentShare = request.POST['gymAgentShare']
                        userInformation.save()
                        print(userInformation.userType,"23456765434565456545")
                        if userInformation.userType == "6":
                            gymnames = User.objects.select_related('Organization__id','OrganizationAdress__id').filter(id = userInformation.id).values('organization__gymName','id','organizationAddress__address')
                            if gymnames.exists():
                                for values in gymnames:
                                    val = dict(values)
                                    gymName = val['organization__gymName']
                                    address = val['organizationAddress__address']
                            else:
                                gymName = ''
                                address = ''
                                lat = ''
                                lang = ''
                            if userInformation.phone != None or userInformation.phone != "":
                                phoneNo = userInformation.phone
                            else:
                                phoneNo = False
                            subdeatails = User.objects.get(id=userInformation.id)
                            subject = "Welcome to StratFit."
                            to_email = subdeatails.email
                            ctx = {
                                'gymName':gymName,
                                'email':userInformation.email,
                                'phoneno':phoneNo,
                                'Address':address,
                                'lat':"12345",
                                'lang':"12345",
                                'first_name': subdeatails.email,
                                'password': userInfo['pword']
                            }
                            message = render_to_string('gymRegistration.html', ctx)
                            officeMail(subject, message, to_email)
                        else:
                            subdeatails = User.objects.get(id=userInformation.id)
                            subject = "Welcome to StratFit"
                            to_email = subdeatails.email
                            ctx = {
                                'first_name': subdeatails.first_name,
                                'email':userInfo['email'],
                                'password':userInfo['pword']
                            }
                            message = render_to_string('welcome.html', ctx)
                            officeMail(subject, message, to_email)
                        userAdressInformatioin = UserAddress.objects.create(
                            user_id=userInformation.id
                        )
                        # userAdressInformatioin.user_id = userInformation.id
                        if 'address1' in userInfo and userInfo['address1'] != '' and userInfo['address1'] != None:
                            userAdressInformatioin.address1 = userInfo['address1']
                        if 'address2' in userInfo and userInfo['address2'] != '' and userInfo['address2'] != None:
                            userAdressInformatioin.address2 = userInfo['address2']
                        if 'town' in userInfo and userInfo['town'] != '' and userInfo['town'] != None:
                            userAdressInformatioin.town = userInfo['town']
                        if 'city' in userInfo and userInfo['city'] != '' and userInfo['city'] != None:
                            userAdressInformatioin.city = userInfo['city']
                        if 'state' in userInfo and userInfo['state'] != '' and userInfo['state'] != None:
                            userAdressInformatioin.state = userInfo['state']
                        if 'country' in userInfo and userInfo['country'] != '' and userInfo['country'] != None:
                            userAdressInformatioin.country = userInfo['country']
                        if 'zipCode' in userInfo and userInfo['zipCode'] != '' and userInfo['zipCode'] != None:
                            userAdressInformatioin.zipCode = userInfo['zipCode']
                        if 'timeZone' in userInfo and userInfo['timeZone'] != '' and userInfo['timeZone'] != None:
                            userAdressInformatioin.timeZone = userInfo['timeZone']
                        userAdressInformatioin.save()
                        return JsonResponse({"success": True, "message": " User Created successfully "})
                except Exception:
                    logger.exception("Problem with Creating User")
                    return JsonResponse({"success":False,"message": "Problem with Creating User..."})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

@psa()
def auth_by_token(request, backend):
    print(request.data)
    if backend == 'facebook':
        access_token = request.data.get('access_token', None)
        if access_token is None:
            params = {
                'client_id': request.data.get('clientId'),
                'redirect_uri': request.data.get('redirectUri'),
                'client_secret': settings.SOCIAL_AUTH_FACEBOOK_SECRET,
                'code': request.data.get('code')
            }
            print(params)
            #print('this came here1F')
            print(request.backend.ACCESS_TOKEN_URL)
            # Step 1. Exchange authorization code for access token.
            r = requests.get(request.backend.ACCESS_TOKEN_URL, params=params)
    elif backend == 'google-oauth2':
        payload = dict(client_id=request.data.get('clientId'),
                   redirect_uri=request.data.get('redirectUri'),
                   client_secret=settings.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET,
                   code=request.data.get('code'),
                   grant_type='authorization_code')
        print('this came here1G')
        print(request.backend.ACCESS_TOKEN_URL)
        # Step 1. Exchange authorization code for access token.
        r = requests.post(request.backend.ACCESS_TOKEN_URL, data=payload)
        print(json.loads(r.text),'test----')
    elif backend == 'twitter':
        print('I am twitter')
        AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize'
        '''oauth = OAuth1(settings.SOCIAL_AUTH_TWITTER_KEY,
                  client_secret=settings.SOCIAL_AUTH_TWITTER_SECRET,
                  callback_uri=request.DATA.get('redirectUri'))
        print(oauth)
        r = requests.post(request.backend.REQUEST_TOKEN_URL, auth=oauth)
        print(jsonify(r.text))
        return Response( "User logged in", status=status.HTTP_200_OK )'''
        oauth_client = OAuth1Session(settings.SOCIAL_AUTH_TWITTER_KEY, client_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, callback_uri='http://alpha.stratfit.net')
        try:
            resp = oauth_client.fetch_request_token(request.backend.REQUEST_TOKEN_URL)
            print(resp.get('oauth_token'))
            print(resp.get('oauth_token_secret'))
            url = oauth_client.authorization_url(AUTHORIZATION_URL)
            #webbrowser.open(url)
            return resp.get('oauth_token')
        except ValueError as e:
            raise 'Invalid response from Twitter requesting temp token: {0}'.format(e)
    elif backend == 'linkedin-oauth2':
        access_token_url = 'https://www.linkedin.com/uas/oauth2/accessToken'
        payload = dict(client_id=settings.SOCIAL_AUTH_LINKEDIN_KEY,
                   redirect_uri=request.data.get('redirectUri'),
                   client_secret=settings.SOCIAL_AUTH_LINKEDIN_SECRET,
                   code=request.data.get('code'),
                   grant_type='authorization_code')
        r = requests.post(access_token_url, data=payload)
    #print(r)
    access_tokenFB = request.data.get('access_token', None)
    if access_tokenFB:
        user=request.user
        user = request.backend.do_auth(
            access_token=access_tokenFB,
            user=user.is_authenticated() and user or None
            )
    else:
        access_token = json.loads(r.text)
        #print(json.loads(r.text))
        #print(access_token['access_token'])
        #print('this came here2')
        user=request.user
        user = request.backend.do_auth(
            access_token=access_token['access_token'],
            user=user.is_authenticated() and user or None
            )
    print(user.email,"iam Here")
    #print('this came here')
    createdTime = user.date_joined.strftime("%Y/%m/%d")
    updatedTime = user.updatedDate.strftime("%Y/%m/%d")
    if createdTime == updatedTime:
        user.is_active = True
        updateuser = User.objects.get(pk = user.id)
        updateuser.is_active = True
        '''
        g = GeoIP()
        ip = request.META.get('REMOTE_ADDR', None)
        if ip:
            country = g.country(ip)['country_name']
        else:'''
        country = 'India'  # default city
        countryID = Country.objects.get(name=country)
        counrtycode = countryID.dialCode
        userAdd = UserAddress.objects.filter(user_id = user.id)
        if userAdd.exists():
            if countryID:
                updateUserAdd = UserAddress.objects.get(user_id = user.id)
                updateUserAdd.country=countryID.id
                updateUserAdd.save()
            else:
                updateUserAdd = UserAddress.objects.get(user_id = user.id)
                updateUserAdd.country=190
                updateUserAdd.save()
        else:
            if countryID:
                userCountry = UserAddress.objects.create(
                    user_id=user.id,
                    country=countryID.id
                )
                userCountry.save()
                if countryID == 88:
                    updateuser.currencyType = "INR"
                else:
                    updateuser.currencyType = "USD"
            else:
                userCountry = UserAddress.objects.create(
                    user_id=user.id,
                    country=190
                )
                userCountry.save()
                updateuser.currencyType = "USD"
        updateuser.phoneCode = counrtycode[1:]
        updateuser.save()
    if user and user.is_active:
        #return user# Return anything that makes sense here
        jsonD ={}
        email_id = user.email
        jsonD['email'] = user.email
        jsonD['remote_ip'] = request.META.get('REMOTE_ADDR', None)
        print(email_id,"1234")
        stratauthentication = StartFitAuthentication()
        print(stratauthentication,"gffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
        loginResponse = stratauthentication.authenticate(jsonD)
        print(loginResponse,"jdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd")
        userDataObj = loginResponse
        queryset = User.objects.get(email=email_id)
        username = queryset.username
        androidversion = AppVersion.objects.get(id=1)
        iosversion = AppVersion.objects.get(id=2)
        fitProQuerySet = FitnessProfile.objects.select_related('User__id').filter(user_id=queryset.id).values('gender','dob','height','heightUnit','weight','weightUnit','user_id__id', 'user_id__email', 'user_id__first_name','trainingLevel')
        isProfileSet = False
        dataGoalObj = {}
        dataFitObj = {}
        dataTmaxObj = {}
        if fitProQuerySet.exists():
            isProfileSet = True
            for dt in fitProQuerySet:
                dataFitObj = dict(dt)
                if dataFitObj['dob'] != None:
                    dataFitObj['dob1'] = dataFitObj['dob']
                    dataFitObj['dob'] = dataFitObj['dob'].strftime("%Y/%m/%d %H:%M:%S")
        goalDetails = goals.objects.filter(user = queryset.id ).values()
        isGoalSet = False
        if goalDetails.exists():
            isGoalSet = True
            for dt in goalDetails:
                #print(dt)
                dataGoalObj = dict(dt)
                #print(dataGoalObj)
        PlanDetails = UserPlan.objects.filter(user = queryset.id).filter(status__in = [1,3]).values()
        userCurrency = User.objects.get(id = queryset.id)
        isPlanSet = False
        isTmaxSet = False
        plans = []
        tmaxArr = []
        isFreeTrail = True
        if PlanDetails.exists():
            isFreeTrail = False
            isPlanSet = True
            for dt in PlanDetails:
                planObj = dict(dt)
                downloadUsers = UserPlan.objects.filter(plan_id=planObj['plan_id']).count()
                planInfos = Plan.objects.select_related('Goals__id', 'ProgramType__id', 'User__id').filter(id=planObj['plan_id']).values('id', 'planName', 'createdBy__first_name', 'createdBy__last_name','price', 'duration_weeks', 'ability', 'planGoal__goalName','planDescription', 'programType__programTypeName', 'planStatus','num_of_periods', 'num_of_sessions', 'goals', 'planPhoto','programType_id','createdBy__avatar','licencePolicy','createdBy_id','originalPlanner_id','iosPrice','iosStatus','indianIosPrice','indianPrice')
                for dtp in planInfos:
                    planInfo = dict(dtp)
                    planPurposesVal = PlanGoals.objects.select_related('PlanPurposes').filter(plan_id=planInfo['id']).values('planGoal_id__GoalName')
                    purposes = ''
                    for val in planPurposesVal:
                        valObj = dict(val)
                        purposes += ", " + valObj['planGoal_id__GoalName']
                    if purposes != '':
                        planGoals = purposes[1:]
                    else:
                        planGoals = ""
                    planAbilityVal = SelectedAbilities.objects.select_related('PlanAbilities').filter(plan_id=planInfo['id']).values('ability_id__ability')
                    abilitieslists = ''
                    for val in planAbilityVal:
                        valObj = dict(val)
                        abilitieslists += ", " + valObj['ability_id__ability']
                    if abilitieslists != '':
                        planAbilities = abilitieslists[1:]
                    else:
                        planAbilities = ""
                    planInfo['planPurpose'] = planAbilities
                    planInfo['plan_goals'] = planGoals
                    planInfo['ability'] = planAbilities
                    planInfo['goals'] = planGoals
                    if planInfo['licencePolicy'] == "3" or planInfo['licencePolicy'] == "White-Label":
                        partnerName = User.objects.get(id=planInfo['createdBy_id'])
                        planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
                    else:
                        coachName = User.objects.get(id=planInfo['originalPlanner_id'])
                        planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
                    
                    planInfo['genWarmupVideo'] = 'ztxEOSIcMc4'
                    planInfo['cooldownVideo'] = '2esZzqjO5Cc'
                    planInfo['planUsers'] = downloadUsers
                    print(userDataObj,"userDataOBJ")
                    if 'deviceType' in jsonD and jsonD['deviceType'] =='ios':
                        if userCurrency.currencyType == "INR":
                            if userDataObj['userDetails']['userCountry'] == 88:
                                planInfo['price'] = planInfo['indianIosPrice']
                                planInfo['planPrice'] = planInfo['indianIosPrice']
                                planInfo['iosPrice'] = planInfo['indianIosPrice']
                            else:
                                planInfo['price'] = planInfo['iosPrice']
                                planInfo['planPrice'] = planInfo['iosPrice']
                            if int(planInfo['price']) == 0:
                                planInfo['price'] = "Free"
                        else:
                            if userDataObj['userDetails']['userCountry'] == 88:
                                usdValue = PriceMapping.objects.values().filter(inr=planInfo['indianIosPrice'])
                            else:
                                usdValue = PriceMapping.objects.values().filter(inr=planInfo['iosPrice'])
                            for usd in usdValue:
                                usdObj = dict(usd)
                                dollarVal = usdObj['usd']
                            planInfo['price'] = dollarVal
                            if userDataObj['userDetails']['userCountry'] == 88:
                                planInfo['iosPrice'] = planInfo['indianIosPrice']
                            if int(planInfo['price']) == 0:
                                planInfo['price'] = "Free"
                    else:
                        if int(planInfo['price']) == 0:
                            planInfo['price'] = "Free"
                        else:
                            if userCurrency.currencyType == "INR":
                                if userDataObj['userDetails']['userCountry'] == 88:
                                    planInfo['price'] = (planInfo['indianPrice'])
                                    planInfo['planPrice'] = planInfo['indianPrice']
                                    planInfo['iosPrice'] = planInfo['indianIosPrice']
                                else:
                                    planInfo['price'] = (planInfo['price'])
                                    planInfo['planPrice'] = planInfo['price']
                            else:
                                if userDataObj['userDetails']['userCountry'] == 88:
                                    usdValue = PriceMapping.objects.get(inr=planInfo['indianIosPrice'])
                                    planInfo['iosPrice'] = usdValue.usd
                                    planInfo['price'] = planInfo['indianPrice']
                                    planInfo['planPrice'] = planInfo['indianPrice']
                                else:
                                    usdValue = PriceMapping.objects.get(inr=planInfo['iosPrice'])
                                    planInfo['iosPrice'] = usdValue.usd
                                    planInfo['price'] = planInfo['price']
                                    planInfo['planPrice'] = planInfo['price']
                            if float(planInfo['price']) == 0:
                                planInfo['price'] = "Free"
                                # planInfo['iosPrice'] = round(float(planInfo['iosPrice'])*float(inrValue))
                planObj['info'] = planInfo
                plans.append(planObj)
            tmaxDetails = UserTestPlan.objects.filter(user = queryset.id).values('createdDate', 'exerciseId_id', 'exerciseId_id__exerciseName', 'exerciseName', 'id', 'plan_id', 'tmax', 'updateTmax', 'updateType', 'updatedDate', 'user_id', 'userplan_id', 'workWeight', 'workoutTestDate')
            if tmaxDetails.exists():
                isTmaxSet = True
                for dt in tmaxDetails:
                    #print(dt)
                    dataTmaxObj = dict(dt)
                    tmaxArr.append(dataTmaxObj)
        #print(queryset.email)
        usersessions = UsersValidSessions.objects.filter(user_id=queryset.id).values()
        if usersessions.exists():
            for sess in usersessions:
                sessObj = dict(sess)
                sessKey = sessObj['sessionToken']
                cache.delete(sessKey)
                updatesession = UsersValidSessions.objects.get(id=sessObj['id'])
                updatesession.sessionToken = loginResponse['sessiontoken']
                updatesession.save()
        else:
            createUserSess = UsersValidSessions.objects.create(
                user_id=queryset.id,
                sessionToken=loginResponse['sessiontoken']
            )
            createUserSess.save()
        #print(queryset.email,"This came Here after Authentication")
        x = connection.cursor()
        allExecDetails = "SELECT *,uae.id AS advexId,ue.id as id,uv.videoLink as video_id__videoLink FROM `utility_exercise` ue LEFT JOIN `utility_advexercises` uae ON ue.id = uae.exercise_id LEFT JOIN `utility_videos` uv ON uv.id = ue.video_id WHERE ue.id IS NOT NULL AND ue.accessLevel = 0 AND ue.exerciseStatus =1"
        x.execute(allExecDetails)
        resultQuery = dictfetchall(x)
        PlanExercises = []
        for dt7 in resultQuery:
            dataExObj = dict(dt7)
            PlanExercises.append(dataExObj)
        defaultTmax = defaultTmaxValues(queryset.id, PlanExercises)
        if defaultTmax != []:
            for ex1 in PlanExercises:
                exId = ex1['id']
                firstTemp = False
                for dex in defaultTmax:
                    if dex['exId'] == exId:
                        ex1['defaultTmax'] = dex['tmaxVal']
                        firstTemp = True
                    elif firstTemp == False:
                        ex1['defaultTmax'] = 0
        if queryset.email is not None:
            request.session['loggedIn'] = True
            request.session['email'] = queryset.email
            request.session['user_id'] = queryset.id
            request.session['first_name'] = queryset.first_name
        return JsonResponse({"Exercises":PlanExercises,"success":True,"message": "Logged In successfully", "profile":dataFitObj, "goals":dataGoalObj, "tmax":tmaxArr, "plans":plans, "isProfileSet":isProfileSet, "isGoalSet":isGoalSet, "isPlanSet":isPlanSet, "isTmaxSet":isTmaxSet,"code":loginResponse['code'],"sessiontoken":loginResponse['sessiontoken'],"privacy":queryset.userPrivacy,"userDetails":userDataObj['userDetails']['email'],"username":username,"user_id":userDataObj['userDetails']['id'],"is_superuser":userDataObj['userDetails']['is_superuser'],"is_active":userDataObj['userDetails']['is_active'],"first_name":userDataObj['userDetails']['first_name'],"last_name":userDataObj['userDetails']['last_name'],"userType":userDataObj['userDetails']['userType'],"avatar":userDataObj['userDetails']['avatar'],"otp":userDataObj['userDetails']['otp'],"orgId":userDataObj['userDetails']['organization'],"isFreeTrail":isFreeTrail,"phone":userDataObj['userDetails']['phone'],"currencyType":userDataObj['userDetails']['currencyType'],"email":queryset.email,"phonecode":userDataObj['userDetails']['phoneCode'],"coverImage":userDataObj['userDetails']['userCover'],"fname":userDataObj['userDetails']['first_name'],"lname":userDataObj['userDetails']['last_name'],"androidVersion":androidversion.version,"iosVersion":iosversion.version,"generalWarmup":[{"Name":"Hip Circles","Reps":5,"ExTime":"Not Applicable","Direction":"Both","Equipment":"Not Applicable"},{"Name":"Knee Circles","Reps":10,"ExTime":"Not Applicable","Direction":"Both","Equipment":"Not Applicable"},{"Name":"Standing lower back release","Reps":10,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Not Applicable"},{"Name":"Roll overs","Reps":10,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Not Applicable"},{"Name":"Fire Hydrant Circles","Reps":10,"ExTime":"Not Applicable","Direction":"Each leg / Direction","Equipment":"Not Applicable"},{"Name":"Foam Rolling - Back","Reps":8,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Foam Roller"},{"Name":"IT Band","Reps":8,"ExTime":"Not Applicable","Direction":"Each leg","Equipment":"Foam Roller"},{"Name":"Adductors","Reps":8,"ExTime":"Not Applicable","Direction":"Each leg","Equipment":"Foam Roller"},{"Name":"Ball Rolling (Cricket / Baseball)","Reps":0,"ExTime":"30","Direction":"Each side","Equipment":"Cricket / Baseball"},{"Name":"Arm Swings - Over under","Reps":10,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Not Applicable"}], "Cooldown":[{"name":"FLoor Quadraceps Stretch"},{"name":"Floor Glute Stretch"},{"name":"Neck, Back, and Hamstring Stretch"},{"name":"Classic Hamstring Stretch"},{"name":"Shoulders and Biceps Stretch"},{"name":"Lower Back Stretch"},{"name":"Frog Stretch"},{"name":"Cat Stretch"},{"name":"Triceps and Lat Reach Stretch"}], "exerciseWarmup":{"strength":[{"Sets":1,"Reps":10,"intensity":50},{"Sets":1,"Reps":6,"intensity":60},{"Sets":1,"Reps":4,"intensity":70},{"Sets":1,"Reps":3,"intensity":80},{"Sets":1,"Reps":1,"intensity":90}],"explosive":[{"Sets":1,"Reps":5,"intensity":50},{"Sets":1,"Reps":5,"intensity":50},{"Sets":1,"Reps":3,"intensity":60},{"Sets":1,"Reps":3,"intensity":60},{"Sets":1,"Reps":3,"intensity":70},{"Sets":1,"Reps":1,"intensity":80},{"Sets":1,"Reps":1,"intensity":90}]}})
    else:
        return JsonResponse({"success":False,"message": "User not active"})
          
@csrf_exempt
@api_view(['POST'])
@permission_classes((permissions.AllowAny,))
def social_register(request):
    auth_token = request.data.get('code', None)
    backend = request.data.get('backend', None)
    #print(backend)
    if backend:
        print('Where I am')
        #print(backend)
        try:
            user = register_by_access_token(request, backend)
        except Exception as err:
            #print('There is error')
            #return Response( "User logged in", status=status.HTTP_200_OK )
            return Response(str(err), status=400)
        if User:
            strategy = load_strategy(request=request)
            _do_login(backend, user, user.social_user)
            return HttpResponse(user)
        else:
            return Response("Bad Credentials", status=403)
    elif request.data.get('name', None) == 'apple':
        print('In Twitter')
        try:
            token = (request, 'twitter')
        except Exception as err:
            return Response(str(err), status=400)
        if token:
            #strategy = load_strategy(request=request)
            #_do_login(backend, user, user.social_user)
            print(token)
            return Response( {"oauth_token":token}, status=status.HTTP_200_OK )
        else:
            return Response("Bad Credentials", status=403)
    else:
        return Response("Bad request", status=400)
		
		
@csrf_exempt
@api_view(['POST'])
@permission_classes((permissions.AllowAny,))
def social_core_register(request):
    auth_token = request.data.get('code', None)
    backend = request.data.get('backend', None)
    #print(backend)
    if backend:
        #print('Where I am')
        #print(backend)
        try:
            user = register_by_access_token(request, backend)
        except Exception as err:
            #print('There is error')
            #return Response( "User logged in", status=status.HTTP_200_OK )
            return Response(str(err), status=400)
        if User:
            #strategy = load_strategy(request=request)
            #_do_login(backend, user, user.social_user)
            return HttpResponse(user)
        else:
            return Response("Bad Credentials", status=403)
    elif request.data.get('name', None) == 'twitter':
        print('In Twitter')
        try:
            token = register_by_access_token(request, 'twitter')
        except Exception as err:
            return Response(str(err), status=400)
        if token:
            #strategy = load_strategy(request=request)
            #_do_login(backend, user, user.social_user)
            print(token)
            return Response( {"oauth_token":token}, status=status.HTTP_200_OK )
        else:
            return Response("Bad Credentials", status=403)
    else:
        return Response("Bad request", status=400)
        
'''
@psa()
def register_by_access_token(request,backend):
    # This view expects an access_token GET parameter, if it's needed,
    # request.backend and request.strategy will be loaded with the current
    # backend and strategy.
    
    token = request.data.get('access_token')
    print(token,"heteteeeeeeeeeeeeeeeee")
    
    print(backend,"hffffffffffffffffffffffffffff")
    user = request.backend.do_auth(token)
    print(user,"jdddsssssssssssssssssssssssss")
    if user:
        #login(request, user)
        return 'OK'
    else:
        return 'ERROR'
'''        
@psa()
def register_by_access_token(request,backend):
    print(request.data)
    if backend == 'facebook':
        access_token = request.data.get('access_token', None)
        if access_token is None:
            params = {
                'client_id': request.data.get('clientId'),
                'redirect_uri': request.data.get('redirectUri'),
                'client_secret': settings.SOCIAL_AUTH_FACEBOOK_SECRET,
                'code': request.data.get('code')
            }
            print(params)
            #print('this came here1F')
            print(request.backend.ACCESS_TOKEN_URL)
            # Step 1. Exchange authorization code for access token.
            r = requests.get(request.backend.ACCESS_TOKEN_URL, params=params)
    elif backend == 'apple-id':
        print("heereererer")
        access_token_url = 'https://appleid.apple.com/auth/token'
        payload = dict(client_id=settings.SOCIAL_AUTH_APPLE_ID_CLIENT,
                   redirect_uri=request.data.get('redirectUri'),
                   client_secret=settings.SOCIAL_AUTH_APPLE_ID_SECRET,
                   code=request.data.get('code'),
                   grant_type='authorization_code')
        r = requests.post(access_token_url, data=payload)        
    elif backend == 'google-oauth2':
        payload = dict(client_id=request.data.get('clientId'),
                   redirect_uri=request.data.get('redirectUri'),
                   client_secret=settings.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET,
                   code=request.data.get('code'),
                   grant_type='authorization_code')
        print('this came here1G')
        print(request.backend.ACCESS_TOKEN_URL)
        # Step 1. Exchange authorization code for access token.
        r = requests.post(request.backend.ACCESS_TOKEN_URL, data=payload)
        print(json.loads(r.text),'test----')
    elif backend == 'twitter':
        print('I am twitter')
        AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize'
        '''oauth = OAuth1(settings.SOCIAL_AUTH_TWITTER_KEY,
                  client_secret=settings.SOCIAL_AUTH_TWITTER_SECRET,
                  callback_uri=request.DATA.get('redirectUri'))
        print(oauth)
        r = requests.post(request.backend.REQUEST_TOKEN_URL, auth=oauth)
        print(jsonify(r.text))
        return Response( "User logged in", status=status.HTTP_200_OK )'''
        oauth_client = OAuth1Session(settings.SOCIAL_AUTH_TWITTER_KEY, client_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, callback_uri='http://alpha.stratfit.net')
        try:
            resp = oauth_client.fetch_request_token(request.backend.REQUEST_TOKEN_URL)
            print(resp.get('oauth_token'))
            print(resp.get('oauth_token_secret'))
            url = oauth_client.authorization_url(AUTHORIZATION_URL)
            #webbrowser.open(url)
            return resp.get('oauth_token')
        except ValueError as e:
            raise 'Invalid response from Twitter requesting temp token: {0}'.format(e)
    elif backend == 'linkedin-oauth2':
        access_token_url = 'https://www.linkedin.com/uas/oauth2/accessToken'
        payload = dict(client_id=settings.SOCIAL_AUTH_LINKEDIN_KEY,
                   redirect_uri=request.data.get('redirectUri'),
                   client_secret=settings.SOCIAL_AUTH_LINKEDIN_SECRET,
                   code=request.data.get('code'),
                   grant_type='authorization_code')
        r = requests.post(access_token_url, data=payload)
    
    token = request.data.get('access_token',None)
    if token:
        print("hhhhhhhhhhhhhhhhhhhhhhhhhhhhh")
        user=request.user
        user =request.backend.do_auth(
            access_token=token,
            user=user.is_authenticated() and user or None
            )
    else:
        access_token = json.loads(r.text)
        print(json.loads(r.text))
        #print(access_token['access_token'])
        #print('this came here2')
        user=request.user
        user = request.backend.do_auth(
            access_token=access_token['access_token'],
            user=user.is_authenticated() and user or None
            )
    print(user.email,"iam Here")
    #print('this came here')
    createdTime = user.date_joined.strftime("%Y/%m/%d")
    updatedTime = user.updatedDate.strftime("%Y/%m/%d")
    if createdTime == updatedTime:
        user.is_active = True
        updateuser = User.objects.get(pk = user.id)
        updateuser.is_active = True
        '''
        g = GeoIP()
        ip = request.META.get('REMOTE_ADDR', None)
        if ip:
            country = g.country(ip)['country_name']
        else:'''
        country = 'India'  # default city
        countryID = Country.objects.get(name=country)
        counrtycode = countryID.dialCode
        userAdd = UserAddress.objects.filter(user_id = user.id)
        if userAdd.exists():
            if countryID:
                updateUserAdd = UserAddress.objects.get(user_id = user.id)
                updateUserAdd.country=countryID.id
                updateUserAdd.save()
            else:
                updateUserAdd = UserAddress.objects.get(user_id = user.id)
                updateUserAdd.country=190
                updateUserAdd.save()
        else:
            if countryID:
                userCountry = UserAddress.objects.create(
                    user_id=user.id,
                    country=countryID.id
                )
                userCountry.save()
                if countryID == 88:
                    updateuser.currencyType = "INR"
                else:
                    updateuser.currencyType = "USD"
            else:
                userCountry = UserAddress.objects.create(
                    user_id=user.id,
                    country=190
                )
                userCountry.save()
                updateuser.currencyType = "USD"
        updateuser.phoneCode = counrtycode[1:]
        updateuser.save()
    if user and user.is_active:
        #return user# Return anything that makes sense here
        jsonD ={}
        email_id = user.email
        jsonD['email'] = user.email
        jsonD['remote_ip'] = request.META.get('REMOTE_ADDR', None)
        print(email_id,"1234")
        stratauthentication = StartFitAuthentication()
        loginResponse = stratauthentication.authenticate(jsonD)
        print(loginResponse)
        userDataObj = loginResponse
        queryset = User.objects.get(email=email_id)
        username = queryset.username
        androidversion = AppVersion.objects.get(id=1)
        iosversion = AppVersion.objects.get(id=2)
        fitProQuerySet = FitnessProfile.objects.select_related('User__id').filter(user_id=queryset.id).values('gender','dob','height','heightUnit','weight','weightUnit','user_id__id', 'user_id__email', 'user_id__first_name','trainingLevel')
        print(fitProQuerySet.query)
        isProfileSet = False
        dataGoalObj = {}
        dataFitObj = {}
        dataTmaxObj = {}
        if fitProQuerySet.exists():
            for dt in fitProQuerySet:
                dataFitObj = dict(dt)
                if dataFitObj['dob'] != None:
                    isProfileSet = True
                    dataFitObj['dob1'] = dataFitObj['dob']
                    dataFitObj['dob'] = dataFitObj['dob'].strftime("%Y/%m/%d")
        goalDetails = goals.objects.filter(user = queryset.id ).values()
        isGoalSet = False
        if goalDetails.exists():
            isGoalSet = True
            for dt in goalDetails:
                #print(dt)
                dataGoalObj = dict(dt)
                #print(dataGoalObj)
        PlanDetails = ProgramUserPlan.objects.filter(user = queryset.id).filter(status__in = [1,3]).values()
        userCurrency = User.objects.get(id = queryset.id)
        isPlanSet = False
        isTmaxSet = False
        plans = []
        tmaxArr = []
        isFreeTrail = True
        if PlanDetails.exists():
            isFreeTrail = False
            isPlanSet = True
            for dt in PlanDetails:
                planObj = dict(dt)
                downloadUsers = ProgramUserPlan.objects.filter(plan_id=planObj['plan_id']).count()
                planInfos = ProgramPlan.objects.select_related('Goals__id', 'ProgramType__id', 'User__id').filter(id=planObj['plan_id']).values('id', 'planName', 'createdBy__first_name', 'createdBy__last_name','price', 'duration_weeks', 'ability', 'planGoal__goalName','planDescription', 'programType__programTypeName', 'planStatus','num_of_periods', 'num_of_sessions', 'goals', 'planPhoto','programType_id','createdBy__avatar','licencePolicy','createdBy_id','originalPlanner_id','iosPrice','iosStatus','indianIosPrice','indianPrice')
                for dtp in planInfos:
                    planInfo = dict(dtp)
                    planPurposesVal = ProgramPlanGoals.objects.select_related('PlanPurposes').filter(plan_id=planInfo['id']).values('planGoal_id__GoalName')
                    purposes = ''
                    for val in planPurposesVal:
                        valObj = dict(val)
                        purposes += ", " + valObj['planGoal_id__GoalName']
                    if purposes != '':
                        planGoals = purposes[1:]
                    else:
                        planGoals = ""
                    planAbilityVal = ProgramSelectedAbilities.objects.select_related('PlanAbilities').filter(plan_id=planInfo['id']).values('ability_id__ability')
                    abilitieslists = ''
                    for val in planAbilityVal:
                        valObj = dict(val)
                        abilitieslists += ", " + valObj['ability_id__ability']
                    if abilitieslists != '':
                        planAbilities = abilitieslists[1:]
                    else:
                        planAbilities = ""
                    planInfo['planPurpose'] = planAbilities
                    planInfo['plan_goals'] = planGoals
                    planInfo['ability'] = planAbilities
                    planInfo['goals'] = planGoals
                    if planInfo['licencePolicy'] == "3" or planInfo['licencePolicy'] == "White-Label":
                        partnerName = User.objects.get(id=planInfo['createdBy_id'])
                        planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
                    else:
                        coachName = User.objects.get(id=planInfo['originalPlanner_id'])
                        planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
                    
                    planInfo['genWarmupVideo'] = 'ztxEOSIcMc4'
                    planInfo['cooldownVideo'] = '2esZzqjO5Cc'
                    planInfo['planUsers'] = downloadUsers
                    print(userDataObj,"userDataOBJ")
                    if 'deviceType' in jsonD and jsonD['deviceType'] =='ios':
                        if userCurrency.currencyType == "INR":
                            if userDataObj['userDetails']['userCountry'] == 88:
                                planInfo['price'] = planInfo['indianIosPrice']
                                planInfo['planPrice'] = planInfo['indianIosPrice']
                                planInfo['iosPrice'] = planInfo['indianIosPrice']
                            else:
                                planInfo['price'] = planInfo['iosPrice']
                                planInfo['planPrice'] = planInfo['iosPrice']
                            if int(planInfo['price']) == 0:
                                planInfo['price'] = "Free"
                        else:
                            if userDataObj['userDetails']['userCountry'] == 88:
                                usdValue = PriceMapping.objects.values().filter(inr=planInfo['indianIosPrice'])
                            else:
                                usdValue = PriceMapping.objects.values().filter(inr=planInfo['iosPrice'])
                            for usd in usdValue:
                                usdObj = dict(usd)
                                dollarVal = usdObj['usd']
                            planInfo['price'] = dollarVal
                            if userDataObj['userDetails']['userCountry'] == 88:
                                planInfo['iosPrice'] = planInfo['indianIosPrice']
                            if int(planInfo['price']) == 0:
                                planInfo['price'] = "Free"
                    else:
                        if int(planInfo['price']) == 0:
                            planInfo['price'] = "Free"
                        else:
                            if userCurrency.currencyType == "INR":
                                if userDataObj['userDetails']['userCountry'] == 88:
                                    planInfo['price'] = (planInfo['indianPrice'])
                                    planInfo['planPrice'] = planInfo['indianPrice']
                                    planInfo['iosPrice'] = planInfo['indianIosPrice']
                                else:
                                    planInfo['price'] = (planInfo['price'])
                                    planInfo['planPrice'] = planInfo['price']
                            else:
                                if userDataObj['userDetails']['userCountry'] == 88:
                                    usdValue = PriceMapping.objects.get(inr=planInfo['indianIosPrice'])
                                    planInfo['iosPrice'] = usdValue.usd
                                    planInfo['price'] = planInfo['indianPrice']
                                    planInfo['planPrice'] = planInfo['indianPrice']
                                else:
                                    usdValue = PriceMapping.objects.get(inr=planInfo['iosPrice'])
                                    planInfo['iosPrice'] = usdValue.usd
                                    planInfo['price'] = planInfo['price']
                                    planInfo['planPrice'] = planInfo['price']
                            if float(planInfo['price']) == 0:
                                planInfo['price'] = "Free"
                                # planInfo['iosPrice'] = round(float(planInfo['iosPrice'])*float(inrValue))
                planObj['info'] = planInfo
                plans.append(planObj)
            tmaxDetails = UserTestPlan.objects.filter(user = queryset.id).values('createdDate', 'exerciseId_id', 'exerciseId_id__exerciseName', 'exerciseName', 'id', 'plan_id', 'tmax', 'updateTmax', 'updateType', 'updatedDate', 'user_id', 'userplan_id', 'workWeight', 'workoutTestDate')
            if tmaxDetails.exists():
                isTmaxSet = True
                for dt in tmaxDetails:
                    #print(dt)
                    dataTmaxObj = dict(dt)
                    tmaxArr.append(dataTmaxObj)
        #print(queryset.email)
        usersessions = UsersValidSessions.objects.filter(user_id=queryset.id).values()
        print("Gender Problem here 2");
        if usersessions.exists():
            for sess in usersessions:
                sessObj = dict(sess)
                sessKey = sessObj['sessionToken']
                cache.delete(sessKey)
                updatesession = UsersValidSessions.objects.get(id=sessObj['id'])
                updatesession.sessionToken = loginResponse['sessiontoken']
                updatesession.save()
        else:
            createUserSess = UsersValidSessions.objects.create(
                user_id=queryset.id,
                sessionToken=loginResponse['sessiontoken']
            )
            createUserSess.save()
        #print(queryset.email,"This came Here after Authentication")
        print("Gender Problem here 3");
        '''x = connection.cursor()
        allExecDetails = "SELECT *,uae.id AS advexId FROM `utility_newexercise` ue LEFT JOIN `utility_advexercises` uae ON ue.id = uae.exercise_id WHERE ue.id IS NOT NULL AND ue.accessLevel = 0 AND ue.exerciseStatus =1"
        x.execute(allExecDetails)
        resultQuery = dictfetchall(x)
        PlanExercises = []
        for dt7 in resultQuery:
            dataExObj = dict(dt7)
            PlanExercises.append(dataExObj)
        print("Gender Problem here 4");
        defaultTmax = defaultTmaxValues(queryset.id, PlanExercises)
        print("Gender Problem here 5");
        if defaultTmax != []:
            for ex1 in PlanExercises:
                exId = ex1['id']
                firstTemp = False
                for dex in defaultTmax:
                    if dex['exId'] == exId:
                        ex1['defaultTmax'] = dex['tmaxVal']
                        firstTemp = True
                    elif firstTemp == False:
                        ex1['defaultTmax'] = 0'''
        if queryset.email is not None:
            request.session['loggedIn'] = True
            request.session['email'] = queryset.email
            request.session['user_id'] = queryset.id
            request.session['first_name'] = queryset.first_name
        return JsonResponse({"success":True,"message": "Logged In successfully", "profile":dataFitObj, "goals":dataGoalObj, "tmax":tmaxArr, "plans":plans, "isProfileSet":isProfileSet, "isGoalSet":isGoalSet, "isPlanSet":isPlanSet, "isTmaxSet":isTmaxSet,"code":loginResponse['code'],"sessiontoken":loginResponse['sessiontoken'],"privacy":queryset.userPrivacy,"userDetails":userDataObj['userDetails']['email'],"username":username,"user_id":userDataObj['userDetails']['id'],"is_superuser":userDataObj['userDetails']['is_superuser'],"is_active":userDataObj['userDetails']['is_active'],"first_name":userDataObj['userDetails']['first_name'],"last_name":userDataObj['userDetails']['last_name'],"userType":userDataObj['userDetails']['userType'],"avatar":userDataObj['userDetails']['avatar'],"otp":userDataObj['userDetails']['otp'],"orgId":userDataObj['userDetails']['organization'],"isFreeTrail":isFreeTrail,"phone":userDataObj['userDetails']['phone'],"currencyType":userDataObj['userDetails']['currencyType'],"email":queryset.email,"phonecode":userDataObj['userDetails']['phoneCode'],"coverImage":userDataObj['userDetails']['userCover'],"fname":userDataObj['userDetails']['first_name'],"lname":userDataObj['userDetails']['last_name'],"androidVersion":androidversion.version,"iosVersion":iosversion.version,"generalWarmup":[{"Name":"Hip Circles","Reps":5,"ExTime":"Not Applicable","Direction":"Both","Equipment":"Not Applicable"},{"Name":"Knee Circles","Reps":10,"ExTime":"Not Applicable","Direction":"Both","Equipment":"Not Applicable"},{"Name":"Standing lower back release","Reps":10,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Not Applicable"},{"Name":"Roll overs","Reps":10,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Not Applicable"},{"Name":"Fire Hydrant Circles","Reps":10,"ExTime":"Not Applicable","Direction":"Each leg / Direction","Equipment":"Not Applicable"},{"Name":"Foam Rolling - Back","Reps":8,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Foam Roller"},{"Name":"IT Band","Reps":8,"ExTime":"Not Applicable","Direction":"Each leg","Equipment":"Foam Roller"},{"Name":"Adductors","Reps":8,"ExTime":"Not Applicable","Direction":"Each leg","Equipment":"Foam Roller"},{"Name":"Ball Rolling (Cricket / Baseball)","Reps":0,"ExTime":"30","Direction":"Each side","Equipment":"Cricket / Baseball"},{"Name":"Arm Swings - Over under","Reps":10,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Not Applicable"}], "Cooldown":[{"name":"FLoor Quadraceps Stretch"},{"name":"Floor Glute Stretch"},{"name":"Neck, Back, and Hamstring Stretch"},{"name":"Classic Hamstring Stretch"},{"name":"Shoulders and Biceps Stretch"},{"name":"Lower Back Stretch"},{"name":"Frog Stretch"},{"name":"Cat Stretch"},{"name":"Triceps and Lat Reach Stretch"}], "exerciseWarmup":{"strength":[{"Sets":1,"Reps":10,"intensity":50},{"Sets":1,"Reps":6,"intensity":60},{"Sets":1,"Reps":4,"intensity":70},{"Sets":1,"Reps":3,"intensity":80},{"Sets":1,"Reps":1,"intensity":90}],"explosive":[{"Sets":1,"Reps":5,"intensity":50},{"Sets":1,"Reps":5,"intensity":50},{"Sets":1,"Reps":3,"intensity":60},{"Sets":1,"Reps":3,"intensity":60},{"Sets":1,"Reps":3,"intensity":70},{"Sets":1,"Reps":1,"intensity":80},{"Sets":1,"Reps":1,"intensity":90}]}})
    else:
        return JsonResponse({"success":False,"message": "User not active"})
@psa()
def auth_by_token_new(request, backend):
    print(request.data)
    if backend == 'facebook':
        access_token = request.data.get('access_token', None)
        if access_token is None:
            params = {
                'client_id': request.data.get('clientId'),
                'redirect_uri': request.data.get('redirectUri'),
                'client_secret': settings.SOCIAL_AUTH_FACEBOOK_SECRET,
                'code': request.data.get('code')
            }
            print(params)
            #print('this came here1F')
            print(request.backend.ACCESS_TOKEN_URL)
            # Step 1. Exchange authorization code for access token.
            r = requests.get(request.backend.ACCESS_TOKEN_URL, params=params)
    elif backend == 'google-oauth2':
        payload = dict(client_id=request.data.get('clientId'),
                   redirect_uri=request.data.get('redirectUri'),
                   client_secret=settings.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET,
                   code=request.data.get('code'),
                   grant_type='authorization_code')
        print('this came here1G')
        print(request.backend.ACCESS_TOKEN_URL)
        # Step 1. Exchange authorization code for access token.
        r = requests.post(request.backend.ACCESS_TOKEN_URL, data=payload)
        print(json.loads(r.text),'test----')
    elif backend == 'twitter':
        print('I am twitter')
        AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize'
        '''oauth = OAuth1(settings.SOCIAL_AUTH_TWITTER_KEY,
                  client_secret=settings.SOCIAL_AUTH_TWITTER_SECRET,
                  callback_uri=request.DATA.get('redirectUri'))
        print(oauth)
        r = requests.post(request.backend.REQUEST_TOKEN_URL, auth=oauth)
        print(jsonify(r.text))
        return Response( "User logged in", status=status.HTTP_200_OK )'''
        oauth_client = OAuth1Session(settings.SOCIAL_AUTH_TWITTER_KEY, client_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, callback_uri='http://alpha.stratfit.net')
        try:
            resp = oauth_client.fetch_request_token(request.backend.REQUEST_TOKEN_URL)
            print(resp.get('oauth_token'))
            print(resp.get('oauth_token_secret'))
            url = oauth_client.authorization_url(AUTHORIZATION_URL)
            #webbrowser.open(url)
            return resp.get('oauth_token')
        except ValueError as e:
            raise 'Invalid response from Twitter requesting temp token: {0}'.format(e)
    elif backend == 'linkedin-oauth2':
        access_token_url = 'https://www.linkedin.com/uas/oauth2/accessToken'
        payload = dict(client_id=settings.SOCIAL_AUTH_LINKEDIN_KEY,
                   redirect_uri=request.data.get('redirectUri'),
                   client_secret=settings.SOCIAL_AUTH_LINKEDIN_SECRET,
                   code=request.data.get('code'),
                   grant_type='authorization_code')
        r = requests.post(access_token_url, data=payload)
    #print(r)
    access_tokenFB = request.data.get('access_token', None)
    if access_tokenFB:
        user=request.user
        user = request.backend.do_auth(
            access_token=access_tokenFB,
            user=user.is_authenticated() and user or None
            )
    else:
        access_token = json.loads(r.text)
        #print(json.loads(r.text))
        #print(access_token['access_token'])
        #print('this came here2')
        user=request.user
        user = request.backend.do_auth(
            access_token=access_token['access_token'],
            user=user.is_authenticated() and user or None
            )
    print(user.email,"iam Here")
    #print('this came here')
    createdTime = user.date_joined.strftime("%Y/%m/%d")
    updatedTime = user.updatedDate.strftime("%Y/%m/%d")
    if createdTime == updatedTime:
        user.is_active = True
        updateuser = User.objects.get(pk = user.id)
        updateuser.is_active = True

        g = GeoIP2()
        ip = request.META.get('REMOTE_ADDR', None)
        if ip:
            country = g.country(ip)['country_name']
        else:
            country = 'India'  # default city
        countryID = Country.objects.get(name=country)
        counrtycode = countryID.dialCode
        userAdd = UserAddress.objects.filter(user_id = user.id)
        if userAdd.exists():
            if countryID:
                updateUserAdd = UserAddress.objects.get(user_id = user.id)
                updateUserAdd.country=countryID.id
                updateUserAdd.save()
            else:
                updateUserAdd = UserAddress.objects.get(user_id = user.id)
                updateUserAdd.country=190
                updateUserAdd.save()
        else:
            if countryID:
                userCountry = UserAddress.objects.create(
                    user_id=user.id,
                    country=countryID.id
                )
                userCountry.save()
                if countryID == 88:
                    updateuser.currencyType = "INR"
                else:
                    updateuser.currencyType = "USD"
            else:
                userCountry = UserAddress.objects.create(
                    user_id=user.id,
                    country=190
                )
                userCountry.save()
                updateuser.currencyType = "USD"
        updateuser.phoneCode = counrtycode[1:]
        updateuser.save()
    if user and user.is_active:
        #return user# Return anything that makes sense here
        jsonD ={}
        email_id = user.email
        jsonD['email'] = user.email
        jsonD['remote_ip'] = request.META.get('REMOTE_ADDR', None)
        print(email_id,"1234")
        stratauthentication = StartFitAuthentication()
        loginResponse = stratauthentication.authenticate(jsonD)
        print(loginResponse)
        userDataObj = loginResponse
        queryset = User.objects.get(email=email_id)
        username = queryset.username
        androidversion = AppVersion.objects.get(id=1)
        iosversion = AppVersion.objects.get(id=2)
        fitProQuerySet = FitnessProfile.objects.select_related('User__id').filter(user_id=queryset.id).values('gender','dob','height','heightUnit','weight','weightUnit','user_id__id', 'user_id__email', 'user_id__first_name','trainingLevel')
        print(fitProQuerySet.query)
        isProfileSet = False
        dataGoalObj = {}
        dataFitObj = {}
        dataTmaxObj = {}
        if fitProQuerySet.exists():
            for dt in fitProQuerySet:
                dataFitObj = dict(dt)
                if dataFitObj['dob'] != None:
                    isProfileSet = True
                    dataFitObj['dob1'] = dataFitObj['dob']
                    dataFitObj['dob'] = dataFitObj['dob'].strftime("%Y/%m/%d")
        goalDetails = goals.objects.filter(user = queryset.id ).values()
        isGoalSet = False
        if goalDetails.exists():
            isGoalSet = True
            for dt in goalDetails:
                #print(dt)
                dataGoalObj = dict(dt)
                #print(dataGoalObj)
        PlanDetails = ProgramUserPlan.objects.filter(user = queryset.id).filter(status__in = [1,3]).values()
        userCurrency = User.objects.get(id = queryset.id)
        isPlanSet = False
        isTmaxSet = False
        plans = []
        tmaxArr = []
        isFreeTrail = True
        if PlanDetails.exists():
            isFreeTrail = False
            isPlanSet = True
            for dt in PlanDetails:
                planObj = dict(dt)
                downloadUsers = ProgramUserPlan.objects.filter(plan_id=planObj['plan_id']).count()
                planInfos = ProgramPlan.objects.select_related('Goals__id', 'ProgramType__id', 'User__id').filter(id=planObj['plan_id']).values('id', 'planName', 'createdBy__first_name', 'createdBy__last_name','price', 'duration_weeks', 'ability', 'planGoal__goalName','planDescription', 'programType__programTypeName', 'planStatus','num_of_periods', 'num_of_sessions', 'goals', 'planPhoto','programType_id','createdBy__avatar','licencePolicy','createdBy_id','originalPlanner_id','iosPrice','iosStatus','indianIosPrice','indianPrice')
                for dtp in planInfos:
                    planInfo = dict(dtp)
                    planPurposesVal = ProgramPlanGoals.objects.select_related('PlanPurposes').filter(plan_id=planInfo['id']).values('planGoal_id__GoalName')
                    purposes = ''
                    for val in planPurposesVal:
                        valObj = dict(val)
                        purposes += ", " + valObj['planGoal_id__GoalName']
                    if purposes != '':
                        planGoals = purposes[1:]
                    else:
                        planGoals = ""
                    planAbilityVal = ProgramSelectedAbilities.objects.select_related('PlanAbilities').filter(plan_id=planInfo['id']).values('ability_id__ability')
                    abilitieslists = ''
                    for val in planAbilityVal:
                        valObj = dict(val)
                        abilitieslists += ", " + valObj['ability_id__ability']
                    if abilitieslists != '':
                        planAbilities = abilitieslists[1:]
                    else:
                        planAbilities = ""
                    planInfo['planPurpose'] = planAbilities
                    planInfo['plan_goals'] = planGoals
                    planInfo['ability'] = planAbilities
                    planInfo['goals'] = planGoals
                    if planInfo['licencePolicy'] == "3" or planInfo['licencePolicy'] == "White-Label":
                        partnerName = User.objects.get(id=planInfo['createdBy_id'])
                        planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
                    else:
                        coachName = User.objects.get(id=planInfo['originalPlanner_id'])
                        planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
                    
                    planInfo['genWarmupVideo'] = 'ztxEOSIcMc4'
                    planInfo['cooldownVideo'] = '2esZzqjO5Cc'
                    planInfo['planUsers'] = downloadUsers
                    print(userDataObj,"userDataOBJ")
                    if 'deviceType' in jsonD and jsonD['deviceType'] =='ios':
                        if userCurrency.currencyType == "INR":
                            if userDataObj['userDetails']['userCountry'] == 88:
                                planInfo['price'] = planInfo['indianIosPrice']
                                planInfo['planPrice'] = planInfo['indianIosPrice']
                                planInfo['iosPrice'] = planInfo['indianIosPrice']
                            else:
                                planInfo['price'] = planInfo['iosPrice']
                                planInfo['planPrice'] = planInfo['iosPrice']
                            if int(planInfo['price']) == 0:
                                planInfo['price'] = "Free"
                        else:
                            if userDataObj['userDetails']['userCountry'] == 88:
                                usdValue = PriceMapping.objects.values().filter(inr=planInfo['indianIosPrice'])
                            else:
                                usdValue = PriceMapping.objects.values().filter(inr=planInfo['iosPrice'])
                            for usd in usdValue:
                                usdObj = dict(usd)
                                dollarVal = usdObj['usd']
                            planInfo['price'] = dollarVal
                            if userDataObj['userDetails']['userCountry'] == 88:
                                planInfo['iosPrice'] = planInfo['indianIosPrice']
                            if int(planInfo['price']) == 0:
                                planInfo['price'] = "Free"
                    else:
                        if int(planInfo['price']) == 0:
                            planInfo['price'] = "Free"
                        else:
                            if userCurrency.currencyType == "INR":
                                if userDataObj['userDetails']['userCountry'] == 88:
                                    planInfo['price'] = (planInfo['indianPrice'])
                                    planInfo['planPrice'] = planInfo['indianPrice']
                                    planInfo['iosPrice'] = planInfo['indianIosPrice']
                                else:
                                    planInfo['price'] = (planInfo['price'])
                                    planInfo['planPrice'] = planInfo['price']
                            else:
                                if userDataObj['userDetails']['userCountry'] == 88:
                                    usdValue = PriceMapping.objects.get(inr=planInfo['indianIosPrice'])
                                    planInfo['iosPrice'] = usdValue.usd
                                    planInfo['price'] = planInfo['indianPrice']
                                    planInfo['planPrice'] = planInfo['indianPrice']
                                else:
                                    usdValue = PriceMapping.objects.get(inr=planInfo['iosPrice'])
                                    planInfo['iosPrice'] = usdValue.usd
                                    planInfo['price'] = planInfo['price']
                                    planInfo['planPrice'] = planInfo['price']
                            if float(planInfo['price']) == 0:
                                planInfo['price'] = "Free"
                                # planInfo['iosPrice'] = round(float(planInfo['iosPrice'])*float(inrValue))
                planObj['info'] = planInfo
                plans.append(planObj)
            tmaxDetails = UserTestPlan.objects.filter(user = queryset.id).values('createdDate', 'exerciseId_id', 'exerciseId_id__exerciseName', 'exerciseName', 'id', 'plan_id', 'tmax', 'updateTmax', 'updateType', 'updatedDate', 'user_id', 'userplan_id', 'workWeight', 'workoutTestDate')
            if tmaxDetails.exists():
                isTmaxSet = True
                for dt in tmaxDetails:
                    #print(dt)
                    dataTmaxObj = dict(dt)
                    tmaxArr.append(dataTmaxObj)
        #print(queryset.email)
        usersessions = UsersValidSessions.objects.filter(user_id=queryset.id).values()
        print("Gender Problem here 2");
        if usersessions.exists():
            for sess in usersessions:
                sessObj = dict(sess)
                sessKey = sessObj['sessionToken']
                cache.delete(sessKey)
                updatesession = UsersValidSessions.objects.get(id=sessObj['id'])
                updatesession.sessionToken = loginResponse['sessiontoken']
                updatesession.save()
        else:
            createUserSess = UsersValidSessions.objects.create(
                user_id=queryset.id,
                sessionToken=loginResponse['sessiontoken']
            )
            createUserSess.save()
        #print(queryset.email,"This came Here after Authentication")
        print("Gender Problem here 3");
        '''x = connection.cursor()
        allExecDetails = "SELECT *,uae.id AS advexId FROM `utility_newexercise` ue LEFT JOIN `utility_advexercises` uae ON ue.id = uae.exercise_id WHERE ue.id IS NOT NULL AND ue.accessLevel = 0 AND ue.exerciseStatus =1"
        x.execute(allExecDetails)
        resultQuery = dictfetchall(x)
        PlanExercises = []
        for dt7 in resultQuery:
            dataExObj = dict(dt7)
            PlanExercises.append(dataExObj)
        print("Gender Problem here 4");
        defaultTmax = defaultTmaxValues(queryset.id, PlanExercises)
        print("Gender Problem here 5");
        if defaultTmax != []:
            for ex1 in PlanExercises:
                exId = ex1['id']
                firstTemp = False
                for dex in defaultTmax:
                    if dex['exId'] == exId:
                        ex1['defaultTmax'] = dex['tmaxVal']
                        firstTemp = True
                    elif firstTemp == False:
                        ex1['defaultTmax'] = 0'''
        if queryset.email is not None:
            request.session['loggedIn'] = True
            request.session['email'] = queryset.email
            request.session['user_id'] = queryset.id
            request.session['first_name'] = queryset.first_name
        return JsonResponse({"success":True,"message": "Logged In successfully", "profile":dataFitObj, "goals":dataGoalObj, "tmax":tmaxArr, "plans":plans, "isProfileSet":isProfileSet, "isGoalSet":isGoalSet, "isPlanSet":isPlanSet, "isTmaxSet":isTmaxSet,"code":loginResponse['code'],"sessiontoken":loginResponse['sessiontoken'],"privacy":queryset.userPrivacy,"userDetails":userDataObj['userDetails']['email'],"username":username,"user_id":userDataObj['userDetails']['id'],"is_superuser":userDataObj['userDetails']['is_superuser'],"is_active":userDataObj['userDetails']['is_active'],"first_name":userDataObj['userDetails']['first_name'],"last_name":userDataObj['userDetails']['last_name'],"userType":userDataObj['userDetails']['userType'],"avatar":userDataObj['userDetails']['avatar'],"otp":userDataObj['userDetails']['otp'],"orgId":userDataObj['userDetails']['organization'],"isFreeTrail":isFreeTrail,"phone":userDataObj['userDetails']['phone'],"currencyType":userDataObj['userDetails']['currencyType'],"email":queryset.email,"phonecode":userDataObj['userDetails']['phoneCode'],"coverImage":userDataObj['userDetails']['userCover'],"fname":userDataObj['userDetails']['first_name'],"lname":userDataObj['userDetails']['last_name'],"androidVersion":androidversion.version,"iosVersion":iosversion.version,"generalWarmup":[{"Name":"Hip Circles","Reps":5,"ExTime":"Not Applicable","Direction":"Both","Equipment":"Not Applicable"},{"Name":"Knee Circles","Reps":10,"ExTime":"Not Applicable","Direction":"Both","Equipment":"Not Applicable"},{"Name":"Standing lower back release","Reps":10,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Not Applicable"},{"Name":"Roll overs","Reps":10,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Not Applicable"},{"Name":"Fire Hydrant Circles","Reps":10,"ExTime":"Not Applicable","Direction":"Each leg / Direction","Equipment":"Not Applicable"},{"Name":"Foam Rolling - Back","Reps":8,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Foam Roller"},{"Name":"IT Band","Reps":8,"ExTime":"Not Applicable","Direction":"Each leg","Equipment":"Foam Roller"},{"Name":"Adductors","Reps":8,"ExTime":"Not Applicable","Direction":"Each leg","Equipment":"Foam Roller"},{"Name":"Ball Rolling (Cricket / Baseball)","Reps":0,"ExTime":"30","Direction":"Each side","Equipment":"Cricket / Baseball"},{"Name":"Arm Swings - Over under","Reps":10,"ExTime":"Not Applicable","Direction":"Not Applicable","Equipment":"Not Applicable"}], "Cooldown":[{"name":"FLoor Quadraceps Stretch"},{"name":"Floor Glute Stretch"},{"name":"Neck, Back, and Hamstring Stretch"},{"name":"Classic Hamstring Stretch"},{"name":"Shoulders and Biceps Stretch"},{"name":"Lower Back Stretch"},{"name":"Frog Stretch"},{"name":"Cat Stretch"},{"name":"Triceps and Lat Reach Stretch"}], "exerciseWarmup":{"strength":[{"Sets":1,"Reps":10,"intensity":50},{"Sets":1,"Reps":6,"intensity":60},{"Sets":1,"Reps":4,"intensity":70},{"Sets":1,"Reps":3,"intensity":80},{"Sets":1,"Reps":1,"intensity":90}],"explosive":[{"Sets":1,"Reps":5,"intensity":50},{"Sets":1,"Reps":5,"intensity":50},{"Sets":1,"Reps":3,"intensity":60},{"Sets":1,"Reps":3,"intensity":60},{"Sets":1,"Reps":3,"intensity":70},{"Sets":1,"Reps":1,"intensity":80},{"Sets":1,"Reps":1,"intensity":90}]}})
    else:
        return JsonResponse({"success":False,"message": "User not active"})        
@csrf_exempt
@api_view(['POST'])
@permission_classes((permissions.AllowAny,))
def social_register_new(request):
    auth_token = request.data.get('code', None)
    backend = request.data.get('backend', None)
    #print(backend)
    if backend:
        #print('Where I am')
        #print(backend)
        try:
            user = auth_by_token_new(request, backend)
        except Exception as err:
            #print('There is error')
            #return Response( "User logged in", status=status.HTTP_200_OK )
            return Response(str(err), status=400)
        if User:
            #strategy = load_strategy(request=request)
            #_do_login(backend, user, user.social_user)
            return HttpResponse(user)
        else:
            return Response("Bad Credentials", status=403)
    elif request.data.get('name', None) == 'twitter':
        print('In Twitter')
        try:
            token = auth_by_token_new(request, 'twitter')
        except Exception as err:
            return Response(str(err), status=400)
        if token:
            #strategy = load_strategy(request=request)
            #_do_login(backend, user, user.social_user)
            print(token)
            return Response( {"oauth_token":token}, status=status.HTTP_200_OK )
        else:
            return Response("Bad Credentials", status=403)
    else:
        return Response("Bad request", status=400)









@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def fitnessInfo(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url="subscriber/getfitnessinfo/"
    try:
        if username!=None:
            fprofileDetails = FitnessProfile.objects.select_related('User__id').filter(user_id=user).values('gender','dob','height','heightUnit','weight','weightUnit','user_id__id')
            if fprofileDetails.exists():
                dataArr =[]
                for dt in fprofileDetails:
                    dataObj = dict(dt)
                    if dataObj['dob'] != None:
                        dataObj['dob'] = dataObj['dob']. strftime("%Y/%m/%d %H:%M:%S")
                    dataArr.append(dataObj)
                return JsonResponse({"success":True,"details":dataArr})
            else:
                return JsonResponse({"success":False,"result":"Please Enter your Details"})
        else:
            return JsonResponse({"success": False, "message": "User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def fitnessdetails(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url = "subscriber/fitnessdetails/"
    try:
        if username!=None:
            fprofileDetails = FitnessProfile.objects.select_related('User__id').filter(user_id=user).values('gender','dob','height','heightUnit','weight','weightUnit','user_id__id', 'user_id__email', 'user_id__first_name')
            if fprofileDetails.exists():
                dataArr =[]
                for dt in fprofileDetails:
                    dataObj = dict(dt)
                    if dataObj['dob'] != None:
                        dataObj['dob'] = dataObj['dob']. strftime("%Y/%m/%d %H:%M:%S")
                    #dataArr.append(dataObj)
                return JsonResponse({"success":True,"data":dataObj})
            else:
                return JsonResponse({"success":False,"result":"Please Enter your Details"})
        else:
            return JsonResponse({"success": False, "result": "User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def fitnessProfileInfo(request):
    #user = request.session['user_id']
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    profileInfo = json.loads(request.body.decode('utf-8'))
    req = profileInfo
    url = "subscriber/fitnessprofile/"
    try:
        if username!=None:
            fitnessexist = FitnessProfile.objects.filter(user_id=user)
            userProfile = User.objects.get(id = user)
            if 'email' in profileInfo['userInf'] and profileInfo['userInf']['email'] !='' and profileInfo['userInf']['email'] !=None:
                if(userProfile.email != profileInfo['userInf']['email']):
                    userExistObj= User.objects.filter(email = profileInfo['userInf']['email']).exclude(id=profileInfo['id'])
                    if userExistObj.exists():
                        return JsonResponse({"success": False, "message": "Email ID already in use"})
                    else:
                        userProfile.email = profileInfo['userInf']['email']
            if 'first_name' in profileInfo['userInf'] and profileInfo['userInf']['first_name'] !='' and profileInfo['userInf']['first_name'] !=None:
                userProfile.first_name = profileInfo['userInf']['first_name']
            if 'privacy' in profileInfo['userInf'] and profileInfo['userInf']['privacy'] !='' and profileInfo['userInf']['privacy'] !=None:
                userProfile.userPrivacy = profileInfo['userInf']['privacy']
            if 'last_name' in profileInfo['userInf'] and profileInfo['userInf']['last_name'] !='' and profileInfo['userInf']['last_name'] !=None:
                userProfile.last_name = profileInfo['userInf']['last_name']
            if 'phone' in profileInfo['userInf'] and profileInfo['userInf']['phone'] !='' and profileInfo['userInf']['phone'] !=None:
                userProfile.phone = profileInfo['userInf']['phone']
            if 'currencytype' in profileInfo['userInf'] and profileInfo['userInf']['currencytype'] !='' and profileInfo['userInf']['currencytype'] !=None:
                userProfile.currencyType = profileInfo['userInf']['currencytype']
            if 'countrycode' in profileInfo['userInf'] and profileInfo['userInf']['countrycode'] !='' and profileInfo['userInf']['countrycode'] !=None:
                userProfile.phoneCode = profileInfo['userInf']['countrycode']
            userProfile.save()

            if 'countrycode' in profileInfo['userInf'] and profileInfo['userInf']['countrycode'] !='' and profileInfo['userInf']['countrycode'] !=None:
                cntrydata=Country.objects.values('id','name','dialCode','countryCode')
                for dt in cntrydata:
                    cntryObj = dict(dt)
                    print(cntryObj,'===========')
                    if cntryObj['dialCode'] == '+'+profileInfo['userInf']['countrycode']:
                        country_id = cntryObj['id']
                        userAdd = UserAddress.objects.get(user_id = profileInfo['id'])
                        if(userAdd):
                            userAdd.country = country_id
                            userAdd.save()
                        else:
                            userAdds = UserAddress.objects.create(
                                user_id = profileInfo['id'],
                                country = country_id
                            )
                            userAdds.save()

            #print(useraddressExist.exists())
            if(fitnessexist.exists()):
                #print("--------------Update FitnessProfile------------------")
                fitnessprofile = FitnessProfile.objects.get(user_id = profileInfo['id'])
                if 'trainingLevel' in profileInfo['userInf'] and profileInfo['userInf']['trainingLevel'] !='' and profileInfo['userInf']['trainingLevel'] !=None:
                    fitnessprofile.trainingLevel = profileInfo['userInf']['trainingLevel']
                if 'gender' in profileInfo['userInf'] and profileInfo['userInf']['gender'] !='' and profileInfo['userInf']['gender'] !=None:
                    fitnessprofile.gender = profileInfo['userInf']['gender']
                if 'dob' in profileInfo['userInf'] and profileInfo['userInf']['dob'] !='' and profileInfo['userInf']['dob'] !=None:
                    fitnessprofile.dob = profileInfo['userInf']['dob']
                if 'height' in profileInfo['userInf'] and profileInfo['userInf']['height'] !='' and profileInfo['userInf']['height'] !=None:
                    fitnessprofile.height = profileInfo['userInf']['height']
                if 'heightM' in profileInfo['userInf'] and profileInfo['userInf']['heightM'] !='' and profileInfo['userInf']['heightM'] !=None:
                    fitnessprofile.heightUnit = profileInfo['userInf']['heightM']
                if 'weight' in profileInfo['userInf'] and profileInfo['userInf']['weight'] !='' and profileInfo['userInf']['weight'] !=None:
                    print("iam Here",profileInfo['userInf']['weight'])
                    fitnessprofile.weight = profileInfo['userInf']['weight']
                if 'weightM' in profileInfo['userInf'] and profileInfo['userInf']['weightM'] !='' and profileInfo['userInf']['weightM'] !=None:
                    fitnessprofile.weightUnit = profileInfo['userInf']['weightM']
                else:
                    fitnessprofile.weightUnit = "kgs"
                fitnessprofile.save()
                '''
                x = connection.cursor()
                allExecDetails = "SELECT *,uae.id AS advexId,ue.id as id,uv.videoLink as video_id__videoLink FROM `utility_exercise` ue LEFT JOIN `utility_advexercises` uae ON ue.id = uae.exercise_id LEFT JOIN `utility_videos` uv ON uv.id = ue.video_id WHERE ue.id IS NOT NULL AND ue.accessLevel =0 AND ue.exerciseStatus =1"
                x.execute(allExecDetails)
                resultQuery = dictfetchall(x)
                PlanExercises = []
                for dt7 in resultQuery:
                    dataExObj = dict(dt7)
                    PlanExercises.append(dataExObj)
                defaultTmax = defaultTmaxValues(user, PlanExercises)
                if defaultTmax != []:
                    for ex1 in PlanExercises:
                        exId = ex1['id']
                        firstTemp = False
                        for dex in defaultTmax:
                            if dex['exId'] == exId:
                                ex1['defaultTmax'] = dex['tmaxVal']
                                firstTemp = True
                            elif firstTemp == False:
                                ex1['defaultTmax'] = 0
                '''               
                return JsonResponse({"success": True, "message": " Fitness Profile Updated successfully "})
            else:
                #print("--------------Create FitnessProfile------------------")
                fitnessprofile = FitnessProfile.objects.create(
                    user_id = user
                )
                #userAdressInformatioin.user_id = userInformation.id
                #print(profileInfo['userInf']['weight'])
                if 'trainingLevel' in profileInfo['userInf'] and profileInfo['userInf']['trainingLevel'] !='' and profileInfo['userInf']['trainingLevel'] !=None:
                    fitnessprofile.trainingLevel = profileInfo['userInf']['trainingLevel']
                if 'gender' in profileInfo['userInf'] and profileInfo['userInf']['gender'] !='' and profileInfo['userInf']['gender'] !=None:
                    fitnessprofile.gender = profileInfo['userInf']['gender']
                if 'dob' in profileInfo['userInf'] and profileInfo['userInf']['dob'] !='' and profileInfo['userInf']['dob'] !=None:
                    fitnessprofile.dob = profileInfo['userInf']['dob']
                if 'height' in profileInfo['userInf'] and profileInfo['userInf']['height'] !='' and profileInfo['userInf']['height'] !=None:
                    fitnessprofile.height = profileInfo['userInf']['height']
                if 'heightM' in profileInfo['userInf'] and profileInfo['userInf']['heightM'] !='' and profileInfo['userInf']['heightM'] !=None:
                    fitnessprofile.heightUnit = profileInfo['userInf']['heightM']
                if 'weight' in profileInfo['userInf'] and profileInfo['userInf']['weight'] !='' and profileInfo['userInf']['weight'] !=None:
                    print("iam Here",profileInfo['userInf']['weight'])
                    fitnessprofile.weight = profileInfo['userInf']['weight']
                if 'weightM' in profileInfo['userInf'] and profileInfo['userInf']['weightM'] !='' and profileInfo['userInf']['weightM'] !=None:
                    fitnessprofile.weightUnit = profileInfo['userInf']['weightM']
                else:
                    fitnessprofile.weightUnit = "kgs"
                fitnessprofile.save()
                '''
                x = connection.cursor()                
                allExecDetails = "SELECT *,uae.id AS advexId,ue.id as id,uv.videoLink as video_id__videoLink FROM `utility_exercise` ue LEFT JOIN `utility_advexercises` uae ON ue.id = uae.exercise_id LEFT JOIN `utility_videos` uv ON uv.id = ue.video_id WHERE ue.id IS NOT NULL AND ue.accessLevel =0 AND ue.exerciseStatus =1"
                x.execute(allExecDetails)
                resultQuery = dictfetchall(x)
                PlanExercises = []
                for dt7 in resultQuery:
                    dataExObj = dict(dt7)
                    PlanExercises.append(dataExObj)
                defaultTmax = defaultTmaxValues(user, PlanExercises)
                if defaultTmax != []:
                    for ex1 in PlanExercises:
                        exId = ex1['id']
                        firstTemp = False
                        for dex in defaultTmax:
                            if dex['exId'] == exId:
                                ex1['defaultTmax'] = dex['tmaxVal']
                                firstTemp = True
                            elif firstTemp == False:
                                ex1['defaultTmax'] = 0
                '''                
                return JsonResponse({"success": True, "message": " Fitness Profile Saved successfully "})
        else:
            return JsonResponse({"success": False, "message": " User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

def defaultTmaxValues(uid,exercises):
    arr = []
    fitnessInfo =FitnessProfile.objects.get(user_id = uid)
    
    if fitnessInfo.gender!=None:
        genderVal=fitnessInfo.gender
        weightVal=fitnessInfo.weight
        trainingLevelVal=fitnessInfo.trainingLevel
        tmaxInfo = TmaxLookup.objects.filter(gender=genderVal,trainingLevel_id = trainingLevelVal,bodyWeight = weightVal).values()
        for val in tmaxInfo:
            arr.append({"exId":val['exercise_id'],"tmaxVal":val['weight']})
        '''    
        for dt in fitnessInfo:
            dataObj = dict(dt)
            print("here in a loopppppppppppppppp")
            if dataObj['gender'] != None:
                genderVal = dataObj['gender']
                weightVal = dataObj['weight']
                trainingLevelVal = dataObj['trainingLevel']
                exId=[]
                for val in exercises:
                    exId = val['id']
                    print("hereeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
                    #exId.append(val['id'])
                    tmaxInfo = TmaxLookup.objects.filter(gender=genderVal,excercise_id = exId,trainingLevel_id = trainingLevelVal,bodyWeight__gte = weightVal).first()
                    print()
                    if tmaxInfo:
                        #print(tmaxInfo.excercise_id,"-----",tmaxInfo.weight)
                        arr.append({"exId":tmaxInfo.excercise_id,"tmaxVal":tmaxInfo.weight})
    #print(arr,"11111")
    return arr'''
    
    return arr



def getNonce(request):
    blogInfo = json.loads(request.body.decode('utf-8'))
    print(blogInfo['blog']['title'])
    nonceObj = requests.get("http://alpha.stratfit.net/blog/?json=get_nonce&controller=posts&method=create_post")
    print(nonceObj)
    noncedet = nonceObj.json()
    print(noncedet)
    non = noncedet['nonce']
    url = "http://alpha.stratfit.net/blog/?json=create_post&nonce="+non+"&title="+blogInfo['blog']['title']+"&content="+blogInfo['blog']['content']+"&status=publish&author="+blogInfo['blog']['author']+"&categories="+blogInfo['blog']['categories']+""
    postObj = requests.get(url)
    postDetail = postObj.json()
    print(postDetail)
    return JsonResponse({"success":True})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def createtrainerProfile(request):
    #user = request.session['user_id']
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    trainerInfo = json.loads(request.body.decode('utf-8'))
    req = trainerInfo
    url = "subscriber/trainerDetails/"
    try:
        if username!=None:
            print(trainerInfo)
            try:
                trainerDetails = trainerProfile.objects.get(user_id = user)
            except trainerProfile.DoesNotExist:
                trainerDetails = None
            if trainerDetails is not None:
                print("------------Update Trainer------------")
                trainerDetails.aboutTrainer = trainerInfo['trainer']['aboutTrainer']
                trainerDetails.specializations = trainerInfo['trainer']['specializations']
                trainerDetails.accreditations = trainerInfo['trainer']['accreditations']
                trainerDetails.strengthBP = trainerInfo['trainer']['strengthBP']
                trainerDetails.strengthSQAT = trainerInfo['trainer']['strengthSQAT']
                trainerDetails.strengthOP = trainerInfo['trainer']['strengthOP']
                trainerDetails.strengthDL = trainerInfo['trainer']['strengthDL']
                if 'trainerCover' in trainerInfo['trainer'] and trainerInfo['trainer']['trainerCover'] != '':
                    trainerDetails.trainerCover = trainerInfo['trainer']['trainerCover']
                if username['userType'] ==3 or username['userType'] ==1 or username['userType'] ==6:
                    trainerDetails.status = True
                #trainerDetails.status = trainerInfo['trainer']['status']
                trainerDetails.save()
                return JsonResponse({"success": True, "message": " Trainer details updated successfully "})
            else:
                print("--------------Create Trainer------------------")
                trainerInformation = trainerProfile.objects.create(
                    user_id = user,
                    aboutTrainer=trainerInfo['trainer']['aboutTrainer'],
                    specializations=trainerInfo['trainer']['specializations'],
                    trainerCover=trainerInfo['trainer']['trainerCover']
                )
                if 'accreditations' in trainerInfo['trainer'] and trainerInfo['trainer']['accreditations'] !='':
                    trainerInformation.accreditations = trainerInfo['trainer']['accreditations']
                if 'strengthBP' in trainerInfo['trainer'] and trainerInfo['trainer']['strengthBP'] !='':
                    trainerInformation.strengthBP = trainerInfo['trainer']['strengthBP']
                if 'strengthSQAT' in trainerInfo['trainer'] and trainerInfo['trainer']['strengthSQAT'] !='':
                    trainerInformation.strengthSQAT = trainerInfo['trainer']['strengthSQAT']
                if 'strengthOP' in trainerInfo['trainer'] and trainerInfo['trainer']['strengthOP'] !='':
                    trainerInformation.strengthOP = trainerInfo['trainer']['strengthOP']
                if 'strengthDL' in trainerInfo['trainer'] and trainerInfo['trainer']['strengthDL'] !='':
                    trainerInformation.strengthDL = trainerInfo['trainer']['strengthDL']
                if username['userType'] ==3 or username['userType'] ==1 or username['userType'] ==6:
                    trainerInformation.status = True
                    trainerInformation.save()
                else:
                    trainerInformation.status = False
                    trainerInformation.save()
                    trainerobj = trainerProfile.objects.get(pk = trainerInformation.id)
                    #print(trainerobj.aboutTrainer,'+=========+')
                    validateLink = request.META['HTTP_HOST']
                    trainerfirstname = User.objects.get(id = user)
                    randomCode = ''.join(choice('0123456789') for i in range(6))
                    secret_code_plain = str(randomCode)
                    link = "http://"+validateLink+"/services/services/stratservices/subscriber/activateTrainer?code=" + secret_code_plain
                    subject = "Activate trainer profile"
                    #to_email = "narendra.lucky5@gmail.com"
                    to_email ="sujatha@stratfit.co"
                    ctx={
                        'trainername':trainerfirstname.first_name,
                        'trainerid':trainerobj.id,
                        'aboutTrainer':trainerobj.aboutTrainer,
                        'specializations':trainerobj.specializations,
                        'strengthBP':trainerobj.strengthBP,
                        'strengthSQAT':trainerobj.strengthSQAT,
                        'strengthOP':trainerobj.strengthOP,
                        'strengthDL':trainerobj.strengthDL,
                        'userbranding':"http://"+validateLink+"/#/userbranding/"+str(trainerobj.id),
                        'link':link
                    }
                    message = render_to_string('trainerverfication.html',ctx)
                    officeMail(subject, message, to_email)
                    trainerInformation.secretCode = secret_code_plain
                    trainerInformation.save()
                return JsonResponse({"success": True, "message": " Trainer details saved successfully "})
        else:
            return JsonResponse({"success": False, "message": " User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

def activateTrainer(request):
    trainerInfo = request.GET['code']
    print(trainerInfo)
    trainerdata = trainerProfile.objects.filter(secretCode = trainerInfo)
    if trainerdata.exists():
        trainerinf = trainerProfile.objects.filter(secretCode = trainerInfo).values('id','secretCode','status','user_id')
        for dt in trainerinf:
            id = dt['id']
            userid = dt['user_id']
            tdata = trainerProfile.objects.get(pk =id)
            tdata.status =1
            tdata.save()
            updateUserType = User.objects.get(pk = userid)
            updateUserType.userType = 4
            updateUserType.save()
            instanceSub = User.objects.get(id= userid)
            subject = "Profile verification"
            to_email = instanceSub.email
            ctx={
                'trainer_fname':instanceSub.first_name
            }
            message = render_to_string('trainerverficonfirmation.html',ctx)
            officeMail(subject, message, to_email)
        return JsonResponse({"success": True, "message": "Trainer profile verified successfully"})
    else:
        return JsonResponse({"success": True, "message":"Please provide trainer profile"})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def viewTrainerProfile(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    userid = username['id']
    req = "GET"
    url = "subscriber/viewtrainer/"
    try:
        if username!=None:
            trainerDetails = trainerProfile.objects.values('aboutTrainer','specializations','accreditations','strengthBP','strengthSQAT','strengthOP','strengthDL','status','trainerCover').filter(user_id = userid)
            if trainerDetails.exists():
                for dt in trainerDetails:
                    dataObj = dict(dt)
            else:
                dataObj = ''
            return JsonResponse({"success": True, "Details":dataObj})
        else:
            return JsonResponse({"success":False,"message":"User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(userid, req, url, str(e))
        return JsonResponse({"msg":str(e)})


@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def userGoal(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    goalInfo = json.loads(request.body.decode('utf-8'))
    req = goalInfo
    url = "subscriber/userGoal/"

    try:
        if username != None:
            print(goalInfo)
            goalDetails = goals.objects.filter(user=goalInfo['user_id'] )
            if goalDetails.exists():
                details = goals.objects.get(user=goalInfo['user_id'])
                #details.purpose = goalInfo['purpose']
                if 'level' in goalInfo and goalInfo['level']:
                    details.level=goalInfo['level']
                details.save()
            else:
                usergoal = goals.objects.create(
                    #level=goalInfo['level'],
                    #purpose=goalInfo['purpose'],
                    user_id=goalInfo['user_id']
                )
                if 'level' in goalInfo and goalInfo['level'] != "":
                    usergoal.level=goalInfo['level']
                usergoal.save()
            return JsonResponse({"success": True, "message": "Goal Saved Successfully"})
        else:
            return JsonResponse({"success":False,"message":"User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def getUserGoal(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url = "subscriber/getUserGoal/"
    try:
        print(user)
        if username != None:
            userpage =goals.objects.filter(user_id=user).values('level','purpose','user_id')
            if len(userpage) > 0:
                print("Here I am")
                for dt in userpage:
                    print(dt)
                    dataObj = dict(dt)
                    print("dobj",dataObj)
                    return JsonResponse({"success": True, "details": dataObj})
            else:
                return JsonResponse({"success": True, "message": "User does not set their goal"})
        else:
            return JsonResponse({"success": False,"message":"User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def createUserfollow(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    info = json.loads(request.body.decode('utf-8'))
    req = info
    url = "subscriber/createUserfollow/"
    try:
        usertype = User.objects.get(id=info['followerUser_id'])
        if usertype.userType == 8 :
            if user == info['followerUser_id']:
                return JsonResponse({"success": False, "message": "You can not follow yourself"})
            else:
                values=Userfollow.objects.filter(followerUser_id=info['followerUser_id'],followingUser_id=user).values('id','followerUser_id','followingUser_id')
                if values.exists():
                    for val in values:
                        list=dict(val)
                        details = Userfollow.objects.get(id=list['id'])
                        details.followingUser_id = user
                        details.followerUser_id = info['followerUser_id']
                        details.status = info['status']
                        details.save()
                        userfollows = Userfollow.objects.values('id', 'followingUser', 'followerUser', 'status').filter(followingUser=user, followerUser=info['followerUser_id'])
                        ufollow={}
                        if userfollows.exists():
                            for dt3 in userfollows:
                                followObj = dict(dt3)
                                if followObj['followerUser'] == info['followerUser_id']:
                                    ufollow['followStatus'] = followObj['status']
                        return JsonResponse({"success": True, "message": "Details Updated Successfully","celebrities":ufollow})
                else:
                    follow = Userfollow.objects.create(
                        followingUser_id=user,
                        followerUser_id=info['followerUser_id'],
                        status=info['status']
                    )
                    follow.save()
                    userfollows2 = Userfollow.objects.values('id', 'followingUser', 'followerUser', 'status').filter(followingUser=user, followerUser=info['followerUser_id'])
                    ufollows = {}
                    if userfollows2.exists():
                        for dt4 in userfollows2:
                            followObj2 = dict(dt4)
                            if followObj2['followerUser'] == info['followerUser_id']:
                                ufollows['followStatus'] = int(followObj2['status'])
                return JsonResponse({"success": True, "message": "Details Saved Successfully","celebrities":ufollows})
        else:
            return JsonResponse({"success": False, "message": "you are not a celebrity"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})


@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def getUserFallowersFollowing(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url = "subscriber/getUserfollow/"
    try:
        if username != None:
            details = Userfollow.objects.filter(followingUser_id=user).count()
            details1 = Userfollow.objects.filter(followerUser_id=user).count()
            return JsonResponse({"success": True, "NumberOFFollowings": details, "NumberOFFollowers": details1})
        else:
            return JsonResponse({"success":False, "message": "User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def getCountryDetails(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    print(username)
    user = username['id']
    req = "GET"
    url = "subscriber/getCountryDetails/"
    try:
        print(user)
        if username != None:
            data = Country.objects.all().order_by('name').filter(countryStatus = 1)
            dataArr = []
            for dt in data:
                dataObj = model_to_dict(dt)
                dataArr.append(dataObj)
            return HttpResponse(json.dumps(dataArr))
        else:
            return JsonResponse({"success":False,"message":"User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def inviteusers(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    emailslist = json.loads(request.body.decode('utf-8'))
    req = emailslist
    url = "subscriber/inviteusers/"
    try:
        if username != None:
            #print(emailslist,"12456789")
            #email = emailslist['emails'].split(',')
            #for value in email:
            randomCode = ''.join(choice('0123456789') for i in range(6))
            #print(randomCode)
            rand = str(randomCode)
            secret_code_plain = emailslist['email'] + '#' + str(randomCode)
            secret_code_encode = base64.b64encode(secret_code_plain.encode('ascii'))
            existingInvites = Invitations.objects.filter(email = emailslist['email'],userType = 3)
            existingUser = User.objects.filter(email = emailslist['email'])
            if existingUser.exists():
                return JsonResponse({"success": True, "message": "Invitation with this mail-id already accepted or already a user in StratFit"})
            elif 'status' in emailslist !='' or 'status' in emailslist !=None:
                validateLink = request.META['HTTP_HOST']
                link = "http://"+validateLink+"#/acceptinvites/" + secret_code_encode.decode("utf-8")
                subject = "Invitation"
                to_email = emailslist['email']
                ctx = {
                    'first_name': emailslist['name'],
                    'link': link
                }
                message = render_to_string('coachinvitations.html', ctx)
                officeMail(subject, message, to_email)
                return JsonResponse({"success": True, "message": "Invitation sent successfully", })
            elif existingInvites.exists():
                return  JsonResponse({"success":True,"message":"Invitation to this email-id already sent"})
            else:
                createInvitaion = Invitations.objects.create(
                    name = emailslist['name'],
                    email = emailslist['email'],
                    secretCode = secret_code_encode
                )
                createInvitaion.save()
                validateLink = request.META['HTTP_HOST']
                link = "http://"+validateLink+"/#/acceptinvites/"+secret_code_encode.decode("utf-8")
                subject = "Invitation"
                to_email = emailslist['email']
                ctx={
                    'first_name':emailslist['name'],
                    'link':link
                }
                message = render_to_string('coachinvitations.html',ctx)
                officeMail(subject, message, to_email)
                return JsonResponse({"success": True, "message": "Invitation sent successfully",})
        else:
            return JsonResponse({"success": False, "message": "user logged out",})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def inviteMultiEmails(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    emailslist = json.loads(request.body.decode('utf-8'))
    req = emailslist
    url = "subscriber/inviteMultiEmails/"
    try:
        if username != None:
            coachname = User.objects.get(id=username['id'])
            for val in emailslist:
                print(val['name'],"---<>---",val['email'])
                existingInvitations = User.objects.filter(email = val['email'])
                if existingInvitations.exists():
                    print("User Already Exists")
                    message = "Already Accepted the Invitation"
                else:
                    randomCode = ''.join(choice('0123456789') for i in range(6))
                    # print(randomCode)
                    rand = str(randomCode)
                    secret_code_plain = val['email'] + '#' + str(randomCode)
                    secret_code_encode = base64.b64encode(secret_code_plain.encode('ascii'))
                    validateLink = request.META['HTTP_HOST']
                    link = "http://"+validateLink+"/#/acceptinvites/" + secret_code_encode.decode("utf-8")
                    subject = "Invitation"
                    to_email = val['email']
                    ctx = {
                        'first_name': val['name'],
                        'link': link
                    }
                    message = render_to_string('coachinvitations.html', ctx)
                    officeMail(subject, message, to_email)
                    message = "Invitation sent successfully"
            return JsonResponse({"success": True, "message": "Invitations sent successfully"})
        else:
            return JsonResponse({"success":False,"message":"User logged out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

@never_cache
def acceptinvite(request):
    invitations = json.loads(request.body.decode('utf-8'))
    # print(userObjData)
    base64.b64decode(invitations['code'])
    print("came Here TO Print")
    codeDecode = base64.b64decode(invitations['code']).decode("ascii")
    # print(codeDecode)
    codeDecodeSplit = codeDecode.split('#', 1)
    print(codeDecodeSplit)
    # print(codeDecodeSplit[0],"hhhh")
    invitationData = Invitations.objects.filter(email=codeDecodeSplit[0]).values()
    print(invitationData,"pppp")
    if (invitationData.exists()):
        trainerinf = Invitations.objects.filter(email = codeDecodeSplit[0]).values('id','name','email','secretCode')
        for dt in trainerinf:
            dataObj = dict(dt)
            print(dataObj['secretCode'],"123456789")
            passwd = '123abc'
        checktrainer = User.objects.filter(email = dataObj['email']).values()
        if checktrainer.exists():
            return JsonResponse({"success": False, "message": "Already a user. Please Login with your credentials"})
        else:
            createTrainer = User.objects.create(
                first_name = dataObj['name'],
                email = dataObj['email'],
                userType = 3,
                secretCode = dataObj['secretCode'],
                password = make_password(passwd)

            )
            createTrainer.save()
            return JsonResponse({"success": True, "message": "Trainer profile verified successfully","email":codeDecodeSplit[0]})
    else:
        return JsonResponse({"success": False, "message": "Invalid Details"})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def invitedUsersData(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url = "subscriber/invitedUsersData/"
    try:
        if username != None:
            if 'rows' in request.POST and request.POST['rows'] != '':
                rows = int(request.POST['rows'])
            else:
                rows = PAGING_ROWS
            if 'page' in request.POST and request.POST['page'] != '':
                page = int(request.POST['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            invitedData =  Invitations.objects.filter(userType= 3).values('email','name').distinct().order_by('email')
            total = len(invitedData)
            data = invitedData[offset:tot]
            dataArr = list()
            for dt in data:
                dataObj = dict(dt)
                userdata = User.objects.filter(email=dataObj['email'])
                if userdata.exists():
                    dataObj['status'] = "Accepted"
                else:
                    dataObj['status'] = "Invited"
                dataArr.append(dataObj)
            return JsonResponse({"rows": dataArr, "total": total})
        else:
            return JsonResponse({"success": False, "message": "user logged out",})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def invitedCelebData(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url = "subscriber/invitedUsersData/"
    try:
        if username != None:
            if 'rows' in request.POST and request.POST['rows'] != '':
                rows = int(request.POST['rows'])
            else:
                rows = PAGING_ROWS
            if 'page' in request.POST and request.POST['page'] != '':
                page = int(request.POST['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            invitedData =  Invitations.objects.filter(userType= 8).values('email','name').distinct().order_by('email')
            total = len(invitedData)
            data = invitedData[offset:tot]
            dataArr = list()
            for dt in data:
                dataObj = dict(dt)
                userdata = User.objects.filter(email=dataObj['email'])
                if userdata.exists():
                    dataObj['status'] = "Accepted"
                else:
                    dataObj['status'] = "Invited"
                dataArr.append(dataObj)
            return JsonResponse({"rows": dataArr, "total": total})
        else:
            return JsonResponse({"success": False, "message": "user logged out",})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def invitedDataSearch(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    data = json.loads(request.body.decode('utf-8'))
    req = data
    url = "subscriber/invitedDataSearch/"
    try:
        if username != None:
            print(data)
            if 'rows' in data and 'rows' != '':
                rows = int(data['rows'])
            else:
                rows=100

            if 'page' in data and 'page' != '':
                page = int(data['page'])
            else:
                page = 1
            offset = (page-1) * rows
            tot = page * rows
            if 'celebId' in data and data['celebId'] =="8":
                invitefilter = Invitations.objects.filter(userType=8).values('email', 'name').distinct().order_by('email')
            else:
                invitefilter = Invitations.objects.filter(userType=3).values('email','name').distinct().order_by('email')
            if 'email' in data !='' or 'email' in data !=None:
                invitefilter = invitefilter.filter(email__icontains = data['email'])
            if 'name' in data !='' or 'name' in  data != None:
                invitefilter = invitefilter.filter(name__icontains = data['name'])
            ivvitefilter_all = invitefilter
            print(ivvitefilter_all, "this Came Here")
            total = len(ivvitefilter_all)
            invites_filter = ivvitefilter_all[offset:tot]
            print(invites_filter)
            dataArr = list()
            for dt in invites_filter:
                dataObj = dict(dt)
                userdata = User.objects.filter(email = dataObj['email'])
                if userdata.exists():
                    dataObj['status'] = "Accepted"
                else:
                    dataObj['status'] = "Invited"
                dataArr.append(dataObj)
            return JsonResponse({"rows":dataArr,"total":total})
        else:
            return JsonResponse({"success":False,"message":"user Logged Out"})
    except Exception as e:
        logger.error("error")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})

from facepy import GraphAPI

@never_cache
def getFacebookFeed(request):
    post_url ="https://graph.facebook.com/v2.8/me?fields=albums.limit(5)%7Bname%2C%20photos.limit(2)%7D%2Cposts.limit(5)&access_token=EAACEdEose0cBALWVJi0YwU4vZAbnBV9KT57PdaVvNWu3axW84LN27vIsVu6PFlRQV84nSHZB6CrqkSNSRfyHQJhPy1jqCuxvzoLtifg3ZBUqsHmLnhqAvf8l9PSJZCY91JI18VLTLaByePfzRSaFKp3YO1pMndmKSidoPQPTaAgwiKPcszHZCXRpESSJX9oIZD"
    postObj = requests.get(post_url)
    postDetail = postObj.json()
    return JsonResponse(postDetail,safe=False)

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def makeGymSuperUser(request):
    #user = request.session['user_id']
    stratsessionutil = StartFitSessionUtil()
    try:
        username = stratsessionutil.get_user_insession(request)
        data = json.loads(request.body.decode('utf-8'))
        user = username['id']
        if username != None:
            print(data,"in Here")
            for dt in data:
                print(dt,"--<>--")
                gymsuperuser = User.objects.get(pk = dt)
                gymsuperuser.userType = 6
                gymsuperuser.createdBy_id = user
                gymsuperuser.save()

            return JsonResponse({"success":True,"message":"Gym Super User Created Successfully"})
        else:
            return JsonResponse({"success":False,"message":"user logged out"})
    except Exception as e:
        logger.error("error")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def saveSubscriberValidation(request):
    #user = request.session['user_id']
    stratsessionutil = StartFitSessionUtil()
    try:
        username = stratsessionutil.get_user_insession(request)
        data = json.loads(request.body.decode('utf-8'))
        user = username['id']
        if username != None:
            print(data,"in Here")
            if 'id' in data['data'] and data['data']['id'] != '':
                updateDetails = AccountDetails.objects.get(pk=data['data']['id'])
                updateDetails.accountHolderName  = data['data']['accountHolder']
                updateDetails.bankName  = data['data']['bankName']
                updateDetails.accountNumber = data['data']['ac_num']
                updateDetails.bankAdress = data['data']['address']
                updateDetails.swiftCode = data['data']['ifsc']
                updateDetails.ifscCode = data['data']['ifsc']
                updateDetails.default = data['data']['status']
                updateDetails.country = data['data']['ac_country']
                updateDetails.state = data['data']['ac_state']
                updateDetails.city = data['data']['ac_city']
                updateDetails.zipcode = data['data']['ac_zipcode']
                updateDetails.save()
                return JsonResponse({"success":True,"message":"Account details updated successfully"})
            else:
                saveDetails = AccountDetails.objects.create(
                    status = 0,
                    user_id = user,
                    accountHolderName  = data['data']['accountHolder'],
                    #bankName = data['data']['bankName'],
                    accountNumber = data['data']['ac_num'],
                    #bankAdress = data['data']['address']
                )
                if 'bankName' in data['data'] and data['data']['bankName'] != '':
                    saveDetails.bankName = data['data']['bankName']
                if 'address' in data['data'] and data['data']['address'] != '':
                    saveDetails.bankAdress = data['data']['address']
                if 'status' in data['data'] and data['data']['status'] != '':
                    saveDetails.default = data['data']['status']
                if 'swift' in data['data'] and data['data']['ifsc'] != '':
                    saveDetails.swiftCode = data['data']['ifsc']
                if 'ifsc' in data['data'] and data['data']['ifsc'] != '':
                    saveDetails.ifscCode = data['data']['ifsc']
                if 'ac_state' in data['data'] and data['data']['ac_state'] != '':
                    saveDetails.state = data['data']['ac_state']
                if 'ac_country' in data['data'] and data['data']['ac_country'] != '':
                    saveDetails.country = data['data']['ac_country']
                if 'ac_city' in data['data'] and data['data']['ac_city'] != '':
                    saveDetails.city = data['data']['ac_city']
                if 'ac_zipcode' in data['data'] and data['data']['ac_zipcode'] != '':
                    saveDetails.zipcode = data['data']['ac_zipcode']
                saveDetails.save()
                return JsonResponse({"success":True,"message":"Account details saved successfully"})
        else:
            return JsonResponse({"success":False,"message":"user logged out"})
    except Exception as e:
        logger.error("error")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def getAccountDetails(request):
    #user = request.session['user_id']
    stratsessionutil = StartFitSessionUtil()
    try:
        username = stratsessionutil.get_user_insession(request)
        if username != None:
            user = username['id']
            acArr = []
            acDetails = AccountDetails.objects.filter(user_id = user).values()
            for val in acDetails:
                valObj = dict(val)
                acArr.append(valObj)
            return JsonResponse({"success":True,"details":acArr})
        else:
            return JsonResponse({"success":False,"message":"user logged out"})
    except Exception as e:
        logger.error("error")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def getAccountDetails_id(request):
    #user = request.session['user_id']
    stratsessionutil = StartFitSessionUtil()
    data = json.loads(request.body.decode('utf-8'))
    try:
        username = stratsessionutil.get_user_insession(request)
        if username != None:
            user = username['id']
            acArr = []
            acDetails = AccountDetails.objects.filter(user_id = user,id = data['id']).values()
            for val in acDetails:
                valObj = dict(val)
                acArr.append(valObj)
            return JsonResponse({"success":True,"details":acArr})
        else:
            return JsonResponse({"success":False,"message":"user logged out"})
    except Exception as e:
        logger.error("error")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def updateDefaultAccount(request):
    #user = request.session['user_id']
    stratsessionutil = StartFitSessionUtil()
    data = json.loads(request.body.decode('utf-8'))
    try:
        username = stratsessionutil.get_user_insession(request)
        if username != None:
            user = username['id']
            updateAc = AccountDetails.objects.get(pk=data['id'])
            updateAc.default = True
            updateAc.save()
            acDetails = AccountDetails.objects.filter(user_id = user).values().exclude(id = data['id'])
            for val in acDetails:
                valObj = dict(val)
                updateOtherAccounts = AccountDetails.objects.get(pk=valObj ['id'])
                updateOtherAccounts.default = False
                updateOtherAccounts.save()
            return JsonResponse({"success":True,"message":"Default Account"})
        else:
            return JsonResponse({"success":False,"message":"user logged out"})
    except Exception as e:
        logger.error("error")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def trainerInfo(request):
    try:
        data = json.loads(request.body.decode('utf-8'))
        stratsessionutil = StartFitSessionUtil()
        username = stratsessionutil.get_user_insession(request)
        print(data,"qwertg")
        trainervalues = trainerProfile.objects.filter(user_id = data['trainerId']).values('user_id','id','aboutTrainer','specializations','accreditations','strengthBP','strengthSQAT','strengthOP','strengthDL','plansPublished','trainerLikes','trainerCover','user_id__avatar','user__first_name')
        dataArr = list()
        for dt in trainervalues:
            dataObj = dict(dt)
            socialDetails = []
            trainerPlans = []
            followers = Userfollow.objects.filter(followerUser_id=data['trainerId'],status =1).values('followingUser_id', 'followerUser_id')
            print(followers, "1234567890")
            if followers.exists():
                if username is not None:
                    for follower in followers:
                        userfollow = dict(follower)
                        if userfollow['followingUser_id'] == username['id']:
                            #print("followers is Logged In User")
                            dataObj['existingFollowers'] = True
                        else:
                            dataObj['existingFollowers'] = False
                else:
                    dataObj['existingFollowers'] = False
                totalfollowers = len(followers)
            else:
                totalfollowers = 0
            dataObj['totalfollowers'] = totalfollowers
            socialInfo = SocialProfile.objects.filter(user_id = data['trainerId']).values('socailName','id','user_id','socialUrl')
            tplans = Plan.objects.filter(createdBy_id = data['trainerId'],planStatus =1,activationStatus=1).select_related('ProgramType').values('planName','planDescription','price','ability','createdBy_id__avatar','createdBy_id','createdBy_id__first_name','planGoal__goalName','duration_weeks','programType_id__programTypeName','licencePolicy','createdBy_id','originalPlanner_id','iosPrice','iosStatus')
            if socialInfo.exists():
                for val in socialInfo:
                    values = dict(val)
                    socialDetails.append(values)
                    dataObj['socialInfo'] = socialDetails
            else:
                dataObj['socialInfo'] = []
            if tplans.exists():
                for plans in tplans:
                    planObj = dict(plans)
                    if planObj['licencePolicy'] == "3" or planObj['licencePolicy'] == "White-Label":
                        partnerName = User.objects.get(id=planObj['createdBy_id'])
                        planObj['planDescription'] = str(planObj['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
                    else:
                        coachName = User.objects.get(id=planObj['originalPlanner_id'])
                        planObj['planDescription'] = str(planObj['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
                    trainerPlans.append(planObj)
                    dataObj['plans'] = trainerPlans
            else:
                dataObj['plans'] = []
            dataArr.append(dataObj)
        return HttpResponse(json.dumps(dataArr))
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def userBrandingInfo(request):
    try:
        data = json.loads(request.body.decode('utf-8'))
        stratsessionutil = StartFitSessionUtil()
        username = stratsessionutil.get_user_insession(request)
        uservalues = User.objects.filter(id = data['userId']).values('id','avatar','first_name','userType')
        dataArr = list()
        socialDetails = []
        userPlans = []
        tMaxArr = []
        for dt in uservalues:
            dataObj = dict(dt)
            userTmax = UserTestPlan.objects.select_related('User__id','Plan__id','Exercise__id').filter(user_id = data['userId']).values('id','updateTmax','plan_id','exerciseId__exerciseName')
            if userTmax.exists():
                for tmax in userTmax:
                    tmaxValue = dict(tmax)
                    tMaxArr.append(tmaxValue)
                    dataObj['tmax'] = tMaxArr
            else:
                dataObj['tmax'] = tMaxArr
            socialInfo = SocialProfile.objects.filter(user_id = data['userId']).values('socailName','id','user_id','socialUrl')
            if socialInfo.exists():
                for val in socialInfo:
                    values = dict(val)
                    socialDetails.append(values)
                    dataObj['socialInfo'] = socialDetails
            else:
                dataObj['socialInfo'] = []
            followers = Userfollow.objects.filter(followerUser_id=data['userId'], status=1).values(
                'followingUser_id', 'followerUser_id')
            #print(followers, "1234567890")
            if followers.exists():
                if username is not None:
                    for follower in followers:
                        userfollow = dict(follower)
                        if userfollow['followingUser_id'] == username['id']:
                            # print("followers is Logged In User")
                            dataObj['existingFollowers'] = True
                        else:
                            dataObj['existingFollowers'] = False
                else:
                    dataObj['existingFollowers'] = False
                totalfollowers = len(followers)
            else:
                totalfollowers = 0
            dataObj['totalfollowers'] = totalfollowers
            userplandetails = UserPlan.objects.select_related('Plan__id','User__id').filter(user_id = data['userId'],status__in = [1,3]).values('plan_id__planName','plan_id__planDescription','plan_id__price','plan_id__ability','plan_id__createdBy_id__avatar','plan_id__createdBy_id','plan_id__createdBy_id__first_name','plan_id__planGoal__goalName','plan_id__duration_weeks','plan_id__programType_id__programTypeName','plan_id__originalPlanner_id','plan_id__licencePolicy','iosPrice','iosStatus')
            if userplandetails.exists():
                for plan in userplandetails:
                    planObj = dict(plan)
                    if planObj['plan_id__licencePolicy'] == "3" or planObj['plan_id__licencePolicy'] == "White-Label":
                        partnerName = User.objects.get(id=planObj['plan_id__createdBy_id'])
                        planObj['plan_id__planDescription'] = str(planObj['plan_id__planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
                    else:
                        coachName = User.objects.get(id=planObj['plan_id__originalPlanner_id'])
                        planObj['plan_id__planDescription'] = str(planObj['plan_id__planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
                    userPlans.append(planObj)
                    dataObj['plans'] = userPlans
            else:
                dataObj['plans'] = []
            dataArr.append(dataObj)
        return HttpResponse(json.dumps(dataArr))
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def checkLoginWithID(request, format=None):
    lookup_field = 'id'
    model = User
    if request.method == 'GET':
        return JsonResponse({'message' : 'Please use POST with applicable JSON for login service'})
    elif request.method == 'POST':
        userObjData = json.loads(request.body.decode('utf-8'))
        #print(userObjData)
        jsonD = {}
        try:
            instance = User.objects.filter(id=userObjData['id'])
            #print(instance,"pppp")
            if(instance.exists()):
                instanceSub = User.objects.get(id=userObjData['id'])
                instanceSub.is_active = 1
                jsonD['email'] = instanceSub.email
                jsonD['remote_ip'] = request.META.get('REMOTE_ADDR', None)
                #print("here Iam")
                instanceSub.save()
                stratauthentication = StartFitAuthentication()
                loginResponse = stratauthentication.authenticate(jsonD)
                userDataObj = loginResponse
                #print(userDataObj)
                try:
                    if userDataObj['result'] == 'False':
                        #print(userDataObj['message'],"1244")
                        if 'is_active' in userDataObj:
                            return JsonResponse({"success":False, "is_active":0, "message":userDataObj['message']})
                        else:
                            return JsonResponse({"success":False,"message":userDataObj['message']})
                    else:
                        queryset = User.objects.get(email=userDataObj['userDetails']['email'])
                        username = queryset.first_name
                        fitProQuerySet = FitnessProfile.objects.select_related('User__id').filter(user_id=queryset.id).values('gender','dob','height','heightUnit','weight','weightUnit','user_id__id', 'user_id__email', 'user_id__first_name')
                        isProfileSet = False
                        dataGoalObj = {}
                        dataFitObj = {}
                        dataTmaxObj = {}
                        if fitProQuerySet.exists():
                            isProfileSet = True
                            for dt in fitProQuerySet:
                                dataFitObj = dict(dt)
                                if dataFitObj['dob'] != None:
                                    dataFitObj['dob1'] = dataFitObj['dob']
                                    dataFitObj['dob'] = dataFitObj['dob']. strftime("%Y/%m/%d")
                        goalDetails = goals.objects.filter(user = queryset.id ).values()
                        isGoalSet = False
                        if goalDetails.exists():
                            isGoalSet = True
                            for dt in goalDetails:
                                print(dt)
                                dataGoalObj = dict(dt)
                                print(dataGoalObj)
                        PlanDetails = UserPlan.objects.filter(user = queryset.id).filter(status__in = [1,3]).values()
                        userCurrency = User.objects.get(id = queryset.id)
                        isPlanSet = False
                        isTmaxSet = False
                        plans = []
                        tmaxArr = []
                        isFreeTrail = True
                        if PlanDetails.exists():
                            isFreeTrail = False
                            isPlanSet = True
                            for dt in PlanDetails:
                                planObj = dict(dt)
                                downloadUsers = UserPlan.objects.filter(plan_id = planObj['plan_id']).count()
                                planInfos = Plan.objects.select_related('Goals__id','ProgramType__id','User__id').filter(id=planObj['plan_id']).values('id', 'planName', 'createdBy__first_name','createdBy__last_name', 'price', 'duration_weeks','ability', 'planGoal__goalName', 'planDescription','programType__programTypeName', 'planStatus','num_of_periods','num_of_sessions', 'goals','planPhoto', 'programType_id','createdBy__avatar','createdBy_id','originalPlanner_id','licencePolicy','iosPrice','iosStatus','indianIosPrice','indianPrice')
                                for dtp in planInfos:
                                    planInfo = dict(dtp)
                                    planPurposesVal = PlanGoals.objects.select_related('PlanPurposes').filter(plan_id=planInfo['id']).values('planGoal_id__GoalName')
                                    purposes = ''
                                    for val in planPurposesVal:
                                        valObj = dict(val)
                                        purposes += ", " + valObj['planGoal_id__GoalName']
                                    if purposes != '':
                                        planGoals = purposes[1:]
                                    else:
                                        planGoals = ""
                                    planAbilityVal = SelectedAbilities.objects.select_related('PlanAbilities').filter(plan_id=planInfo['id']).values('ability_id__ability')
                                    abilitieslists = ''
                                    for val in planAbilityVal:
                                        valObj = dict(val)
                                        abilitieslists += ", " + valObj['ability_id__ability']
                                    if abilitieslists != '':
                                        planAbilities = abilitieslists[1:]
                                    else:
                                        planAbilities = ""
                                    planInfo['planPurpose'] = planAbilities
                                    planInfo['plan_goals'] = planGoals
                                    planInfo['ability'] = planAbilities
                                    planInfo['goals'] = planGoals
                                    if planInfo['licencePolicy'] == "3" or planInfo['licencePolicy'] == "White-Label":
                                        partnerName = User.objects.get(id=planInfo['createdBy_id'])
                                        planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
                                    else:
                                        coachName = User.objects.get(id=planInfo['originalPlanner_id'])
                                        planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
                                    
                                    planInfo['genWarmupVideo'] = 'ztxEOSIcMc4'
                                    planInfo['cooldownVideo'] = '2esZzqjO5Cc'
                                    planInfo['planUsers'] = downloadUsers
                                    print(userDataObj,"userDataOBJ")
                                    if 'deviceType' in jsonD and jsonD['deviceType'] =='ios':
                                        if userCurrency.currencyType == "INR":
                                            if userDataObj['userDetails']['userCountry'] == 88:
                                                planInfo['price'] = planInfo['indianIosPrice']
                                                planInfo['planPrice'] = planInfo['indianIosPrice']
                                                planInfo['iosPrice'] = planInfo['indianIosPrice']
                                            else:
                                                planInfo['price'] = planInfo['iosPrice']
                                                planInfo['planPrice'] = planInfo['iosPrice']
                                            if int(planInfo['price']) == 0:
                                                planInfo['price'] = "Free"
                                        else:
                                            if userDataObj['userDetails']['userCountry'] == 88:
                                                usdValue = PriceMapping.objects.values().filter(inr=planInfo['indianIosPrice'])
                                            else:
                                                usdValue = PriceMapping.objects.values().filter(inr=planInfo['iosPrice'])
                                            for usd in usdValue:
                                                usdObj = dict(usd)
                                                dollarVal = usdObj['usd']
                                            planInfo['price'] = dollarVal
                                            planInfo['iosPrice'] = planInfo['indianIosPrice']
                                            if int(planInfo['price']) == 0:
                                                planInfo['price'] = "Free"
                                    else:
                                        if int(planInfo['price']) == 0:
                                            planInfo['price'] = "Free"
                                        else:
                                            if userCurrency.currencyType == "INR":
                                                if userDataObj['userDetails']['userCountry'] == 88:
                                                    planInfo['price'] = (planInfo['indianPrice'])
                                                    planInfo['planPrice'] = planInfo['indianPrice']
                                                else:
                                                    planInfo['price'] = (planInfo['price'])
                                                    planInfo['planPrice'] = planInfo['price']
                                            else:
                                                if userDataObj['userDetails']['userCountry'] == 88:
                                                    planInfo['price'] = planInfo['indianPrice']
                                                    planInfo['planPrice'] = planInfo['indianPrice']
                                                else:
                                                    planInfo['price'] = planInfo['price']
                                                    planInfo['planPrice'] = planInfo['price']
                                            if float(planInfo['price']) == 0:
                                                planInfo['price'] = "Free"
                                                # planInfo['iosPrice'] = round(float(planInfo['iosPrice'])*float(inrValue))
                                planObj['info'] = planInfo
                                plans.append(planObj)
                            tmaxDetails = UserTestPlan.objects.filter(user = queryset.id ).values('createdDate', 'exerciseId_id', 'exerciseId_id__exerciseName', 'exerciseName', 'id', 'plan_id', 'tmax', 'updateTmax', 'updateType', 'updatedDate', 'user_id', 'userplan_id', 'workWeight', 'workoutTestDate')
                            if tmaxDetails.exists():
                                isTmaxSet = True
                                for dt in tmaxDetails:
                                    print(dt)
                                    dataTmaxObj = dict(dt)
                                    tmaxArr.append(dataTmaxObj)
                        print(queryset.email)
                        '''for userObj in user:
                            uid = model_to_dict(userObj)
                            print(uid)
                        userRoleID = None'''
                        orgValues = Organization.objects.get(id = queryset.organization_id)
                        orgName = orgValues.gymName
                        usersessions = UsersValidSessions.objects.filter(user_id=queryset.id).values()
                        if usersessions.exists():
                            for sess in usersessions:
                                sessObj = dict(sess)
                                sessKey = sessObj['sessionToken']
                                cache.delete(sessKey)
                                updatesession = UsersValidSessions.objects.get(id=sessObj['id'])
                                updatesession.sessionToken = loginResponse['sessiontoken']
                                updatesession.save()
                        else:
                            createUserSess = UsersValidSessions.objects.create(
                                user_id = queryset.id,
                                sessionToken = loginResponse['sessiontoken']
                            )
                            createUserSess.save()
                        if queryset.email is not None:
                            request.session['loggedIn'] = True
                            request.session['email'] = queryset.email
                            request.session['user_id'] = queryset.id
                            request.session['first_name'] = queryset.first_name
                            request.session['is_superuser'] = queryset.is_superuser
                            return JsonResponse({"success":True,"message": "Logged In successfully", "profile":dataFitObj, "goals":dataGoalObj, "tmax":tmaxArr, "plans":plans, "isProfileSet":isProfileSet, "isGoalSet":isGoalSet, "isPlanSet":isPlanSet, "isTmaxSet":isTmaxSet,"code":loginResponse['code'],"sessiontoken":loginResponse['sessiontoken'],"userDetails":userDataObj['userDetails']['email'],"username":username,"fname":queryset.first_name,"lname":queryset.last_name,"is_superuser":queryset.is_superuser,"is_active":queryset.is_active,"user_id":userDataObj['userDetails']['id'],"userType":queryset.userType,"orgId":queryset.organization_id,"avatar":queryset.avatar,"otp":queryset.otp,"orgName":orgName,"isFreeTrail":isFreeTrail,"phone":userDataObj['userDetails']['phone'],"currencyType":userDataObj['userDetails']['currencyType'],"email":queryset.email,"phonecode":userDataObj['userDetails']['phoneCode'],"coverImage":userDataObj['userDetails']['userCover']})
                except Exception as e:
                    return JsonResponse({"msg":str(e)})
                    JsonResponse("Login attempt failed with user", safe=False)
                    authResponse = AuthResponse()
                    authResponse.code = 401
                    authResponse.message = "Invalid_Credentials"
                    return JsonResponse({"success": False, "message": "Invalid Username Or Password"})
            else:
                return JsonResponse({"success":False, "message":"Sorry, This is not a valid information, contact admin."})
        except exception as e:
            logger.error("Problem with Update User")
            return JsonResponse({"success": False, "message":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def Userfollowers(request):
    #user = request.session['user_id']
    #print(user)
    stratsessionutil = StartFitSessionUtil()
    try:
        username = stratsessionutil.get_user_insession(request)
        print(username)
        user = username['id']
        info = json.loads(request.body.decode('utf-8'))

        usertype = User.objects.get(id=info['followerUser_id'])
        print(usertype.userType,"12345678")
        if usertype.userType == 8 or usertype.userType == 6 or usertype.userType == 4 or usertype.userType == 3 or usertype.userType == 1:
            if user == int(info['followerUser_id']):
                return JsonResponse({"success": False, "message": "You can not follow yourself"})
            if 'status' not in info:
                info['status'] = 1
            values=Userfollow.objects.filter(followerUser_id=info['followerUser_id'],followingUser_id=user).values('id','followerUser_id','followingUser_id')
            print(values,"values")
            if values.exists():
                for val in values:
                    list=dict(val)
                    print(list)
                    details = Userfollow.objects.get(id=list['id'])
                    details.followingUser_id = user
                    details.followerUser_id = info['followerUser_id']
                    details.status = info['status']
                    details.save()
            else:
                follow = Userfollow.objects.create(
                    followingUser_id=user,
                    followerUser_id=info['followerUser_id'],
                    status=info['status']
                )
                follow.save()
            return JsonResponse({"success": True, "message": "details Saved Successfully"})
        else:
            if usertype.userType == 8:
                message = "you are not a celebrity"
            elif usertype.userType == 3:
                message = "you are not a Trainer"
            elif usertype.userType == 6:
                message = "you are not a Gym Super User"
            elif usertype.userType == 1:
                message = "you are not an Admin"
            return JsonResponse({"success": False, "message": message})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg":str(e)})

@never_cache
def planLists(request):
    try:
        planDetails = Plan.objects.select_related('Goals__id','ProgramType__id','User__id').filter(planStatus = 1,activationStatus=1).values('id', 'planName', 'planPhoto', 'price', 'planGoal__goalName', 'planDescription','programType__programTypeName','programType__id','duration_weeks','createdBy','ability','createdBy_id__avatar','createdBy_id__first_name','programType_id','createdBy_id','licencePolicy','originalPlanner_id','iosPrice','iosStatus')
        planArr = []
        planCoaches = []
        planSet = set()
        for dt in planDetails:
            dataObj = dict(dt)
            if dataObj['licencePolicy'] == "3" or dataObj['licencePolicy'] == "White-Label":
                partnerName = User.objects.get(id=dataObj['createdBy_id'])
                dataObj['planDescription'] = str(dataObj['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
            else:
                coachName = User.objects.get(id=dataObj['originalPlanner_id'])
                dataObj['planDescription'] = str(dataObj['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
            planCoaches.append(dataObj['createdBy'])
            planSet.add(dataObj['programType_id'])
        print(planSet)
        for setId in planSet:
            if setId ==1:
                planList = Plan.objects.select_related('Goals__id', 'ProgramType__id', 'User__id').filter(planStatus=1,programType_id = 1,activationStatus=1).values('id', 'planName', 'planPhoto', 'price', 'planGoal__goalName','planDescription', 'programType__programTypeName', 'programType__id','duration_weeks', 'createdBy', 'ability', 'createdBy_id__avatar','createdBy_id__first_name', 'programType_id','createdBy_id','licencePolicy','originalPlanner_id','iosPrice','iosStatus').order_by('-id')[:2]
            if setId ==2:
                planList = Plan.objects.select_related('Goals__id', 'ProgramType__id', 'User__id').filter(planStatus=1,programType_id = 2,activationStatus=1).values('id', 'planName', 'planPhoto', 'price', 'planGoal__goalName','planDescription', 'programType__programTypeName', 'programType__id','duration_weeks', 'createdBy', 'ability', 'createdBy_id__avatar','createdBy_id__first_name', 'programType_id','createdBy_id','licencePolicy','originalPlanner_id','iosPrice','iosStatus').order_by('-id')[:2]
            if setId ==3:
                planList = Plan.objects.select_related('Goals__id', 'ProgramType__id', 'User__id').filter(planStatus=1,programType_id = 3,activationStatus=1).values('id', 'planName', 'planPhoto', 'price', 'planGoal__goalName','planDescription', 'programType__programTypeName', 'programType__id','duration_weeks', 'createdBy', 'ability', 'createdBy_id__avatar','createdBy_id__first_name', 'programType_id','createdBy_id','licencePolicy','originalPlanner_id','iosPrice','iosStatus').order_by('-id')[:2]
            for plan in planList:
                planObj = dict(plan)
                if planObj['licencePolicy'] == "3" or planObj['licencePolicy'] == "White-Label":
                    partnerName = User.objects.get(id=planObj['createdBy_id'])
                    planObj['planDescription'] = str(planObj['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
                else:
                    coachName = User.objects.get(id=planObj['originalPlanner_id'])
                    planObj['planDescription'] = str(planObj['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
                planObj['planPurpose'] =planObj['ability']
                planObj['planType'] = planObj['programType__programTypeName']
                planObj['planCompetency']= "0"
                planObj['planPrice'] = planObj['price']
                planObj['coachId'] = planObj['createdBy']
                planObj['planGoal'] = planObj['planGoal__goalName']
                planObj['planLevel'] = planObj['programType__id']
                
                planObj['planDuration'] = planObj['duration_weeks']
                planObj['coachId'] = planObj['createdBy']
                planArr.append(planObj)
        coachDetails = User.objects.filter(id__in = planCoaches).values()
        coachArr = []
        for coach in coachDetails:
            coach_id = dict(coach)
            coach_id['followers'] = '20'
            if coach_id['avatar'] is not None:
                coach_id['coachThumbnail'] =coach_id['avatar']
            else:
                coach_id['coachThumbnail'] = ''
            coach_id['coachId'] = coach['id']
            coach_id['coachName'] = coach['first_name'] + ' ' + coach['last_name']
            coachPlansArr = []
            plans = Plan.objects.filter(createdBy_id=coach_id['id']).values('id')
            for pl in plans:
                coachPlans = dict(pl)
                coachPlansArr.append(coachPlans['id'])
            coach_id['coachPlans'] = coachPlansArr
            coachArr.append(coach_id)
        return JsonResponse({"success": True, "details": planArr,"allCoaches":coachArr})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def subscribedPlans(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    req = "GET"
    url = "subscriber/subscribedPlan/"
    info = json.loads(request.body.decode('utf-8'))
    try:
        if username != None:
            user = username['id']
            userCurrency = User.objects.get(id=user)
            renewal = False
            subscribedPlan = UserPlan.objects.filter(user_id = user,plan_id = info['plan_id']).select_related('Plan__id').values('plan_id__planName','id','plan_id','status')
            planval = Plan.objects.get(id = info['plan_id'])
            planName = planval.planName
            planId = planval.id
            planPrice = planval.price
            currencyValues = PriceConversion.objects.get(id=1)
            inrValue = currencyValues.inrValue
            if userCurrency.currencyType == "INR":
                if username['userCountry'] == 88:
                    planPrice = planval.indianPrice
            else:
                if username['userCountry'] == 88:
                    planPrice = planval.indianPrice
            iosPrice = planval.iosPrice
            #iosStatus = planval.iosStatus
            freesubscriber = False
            message = "No Plans Subscribed"
            paymentStatus = False
            if subscribedPlan.exists():
                for plan in subscribedPlan:
                    planValues = dict(plan)
                    if planValues['status'] == 1 or planValues['status'] == 3:
                        paymentStatus = 1
                        message = "Already Subscribed to this Plan"
                        print("Active Plan Already Exists")
                    else:
                        paymentStatus = 2
                        message = "Renewal of the active plan"
                        renewal = True
                        print("Plan Renewal")
                #return JsonResponse({"success": True, "details": planValues,"message":"Thank you for subscribing a plan "})
            else:
                userplanexists = UserPlan.objects.filter(user_id = user).values('id')
                if userplanexists.exists():
                    if len(userplanexists) == 1:
                        freesubscriber = True
                    else:
                        freesubscriber =False
                    paymentStatus = 3
                    message = "Thank you for subscribing to plan. Start your one month free Trail "
                    print("Paid Subscription")
                else:
                    paymentStatus = 4
                    message = "Thank you for subscribing to a Plan.Your 28 Days free trial will be activated."
                    print("Free Subscription")
            return JsonResponse({"success":True,"message":message,"paymentStatus":paymentStatus,"planName":planName,"planId":planId,"renewal":renewal,"planPrice":planPrice,"freesubscriber":freesubscriber,"iosPrice":iosPrice})
        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 subscribedPrograms(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    req = "GET"
    url = "subscriber/subscribedPlan/"
    info = json.loads(request.body.decode('utf-8'))
    try:
        if username != None:
            user = username['id']
            userCurrency = User.objects.get(id=user)
            renewal = False
            plans = []
            subscribedPlan = ProgramUserPlan.objects.filter(user_id = user,plan_id = info['plan_id']).select_related('Plan__id').values('plan_id__planName','id','plan_id','status')
            print(subscribedPlan.query)
            planval = ProgramPlan.objects.get(id = info['plan_id'])
            planName = planval.planName
            planDescription = planval.planDescription
            planId = planval.id
            planPrice = planval.price
            currencyValues = PriceConversion.objects.get(id=1)
            inrValue = currencyValues.inrValue
            if userCurrency.currencyType == "INR":
                if username['userCountry'] == 88:
                    planPrice = planval.indianPrice
            else:
                if username['userCountry'] == 88:
                    planPrice = planval.indianPrice
            iosPrice = planval.iosPrice
            #iosStatus = planval.iosStatus
            freesubscriber = False
            message = "No Plans Subscribed"
            paymentStatus = False
            subscriptionDet = {}
            if subscribedPlan.exists():
                PlanDetails = ProgramUserPlan.objects.filter(user = user).filter(status__in = [1,3]).values()
                userCurrency = User.objects.get(id = user)
                isPlanSet = False
                isTmaxSet = False
                plans = []
                tmaxArr = []
                isFreeTrail = True
                if PlanDetails.exists():
                    isFreeTrail = False
                    isPlanSet = True
                    for dt in PlanDetails:
                        planObj = dict(dt)
                        downloadUsers = ProgramUserPlan.objects.filter(plan_id = planObj['plan_id']).count()
                        planInfos = ProgramPlan.objects.select_related('Goals__id','ProgramType__id','User__id').filter(id=planObj['plan_id']).values('id', 'planName', 'createdBy__first_name','createdBy__last_name', 'price', 'duration_weeks','ability', 'planGoal__goalName', 'planDescription','programType__programTypeName', 'planStatus','num_of_periods','num_of_sessions', 'goals','planPhoto', 'programType_id','createdBy__avatar','createdBy_id','originalPlanner_id','licencePolicy','iosPrice','iosStatus','indianIosPrice','indianPrice')
                        for dtp in planInfos:
                            planInfo = dict(dtp)
                            planPurposesVal = ProgramPlanGoals.objects.select_related('PlanPurposes').filter(plan_id=planInfo['id']).values('planGoal_id__GoalName')
                            purposes = ''
                            for val in planPurposesVal:
                                valObj = dict(val)
                                purposes += ", " + valObj['planGoal_id__GoalName']
                            if purposes != '':
                                planGoals = purposes[1:]
                            else:
                                planGoals = ""
                            planAbilityVal = ProgramSelectedAbilities.objects.select_related('PlanAbilities').filter(plan_id=planInfo['id']).values('ability_id__ability')
                            abilitieslists = ''
                            for val in planAbilityVal:
                                valObj = dict(val)
                                abilitieslists += ", " + valObj['ability_id__ability']
                            if abilitieslists != '':
                                planAbilities = abilitieslists[1:]
                            else:
                                planAbilities = ""
                            planInfo['planPurpose'] = planAbilities
                            planInfo['plan_goals'] = planGoals
                            planInfo['ability'] = planAbilities
                            planInfo['goals'] = planGoals
                            if planInfo['licencePolicy'] == "3" or planInfo['licencePolicy'] == "White-Label":
                                partnerName = User.objects.get(id=planInfo['createdBy_id'])
                                planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
                            else:
                                coachName = User.objects.get(id=planInfo['originalPlanner_id'])
                                planInfo['planDescription'] = str(planInfo['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
                            
                            planInfo['genWarmupVideo'] = 'ztxEOSIcMc4'
                            planInfo['cooldownVideo'] = '2esZzqjO5Cc'
                            planInfo['planUsers'] = downloadUsers
                        planObj['info'] = planInfo
                        plans.append(planObj)
                for plan in subscribedPlan:
                    planValues = dict(plan)
                    if planValues['status'] == 1 or planValues['status'] == 3:
                        paymentStatus = 1
                        subscriptionDet = planValues
                        message = "Already Subscribed to this Plan"
                        print("Active Plan Already Exists")
                    else:
                        paymentStatus = 2
                        message = "Renewal of the active plan"
                        renewal = True
                        print("Plan Renewal")
                #return JsonResponse({"success": True, "details": planValues,"message":"Thank you for subscribing a plan "})
            else:
                userplanexists = UserPlan.objects.filter(user_id = user).values('id')
                if userplanexists.exists():
                    if len(userplanexists) == 1:
                        freesubscriber = True
                    else:
                        freesubscriber =False
                    paymentStatus = 3
                    message = "Thank you for subscribing to plan. Start your one month free Trail "
                    print("Paid Subscription")
                else:
                    paymentStatus = 4
                    message = "Thank you for subscribing to a Plan.Your 28 Days free trial will be activated."
                    print("Free Subscription")
            return JsonResponse({"success":True,"message":message,"paymentStatus":paymentStatus,"planName":planName,"planId":planId,"renewal":renewal,"planPrice":planPrice,"freesubscriber":freesubscriber,"iosPrice":iosPrice, "planDescription":planDescription, "subscription":plans})
        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 subscribedPlans1(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    req = "GET"
    url = "subscriber/subscribedPlan/"
    try:
        if username != None:
            user = username['id']
            subscribedPlan = ProgramUserPlan.objects.filter(user_id = user,status= 1).select_related('Plan__id').values('plan_id__planName','id','plan_id')
            if subscribedPlan.exists():
                for plan in subscribedPlan:
                    planValues = dict(plan)
                return JsonResponse({"success": True, "details": planValues,"message":"Thank you for subscribing a plan "})
            else:
                return JsonResponse({"success": False, "message": "Please Subscribe to a Program"})
        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 userlike(request):
    stratsessionutil = StartFitSessionUtil()
    user = stratsessionutil.get_user_insession(request)
    likeinfo = json.loads(request.body.decode('utf-8'))
    try:
        if user != None:
            loginuser_id = user['id']
            exist = UserLikes.objects.filter(likedUser_id=loginuser_id,user_id=likeinfo['profuserid']).values('id')
            if exist.exists():
                return JsonResponse({"success": False, "message": "already liked"})
            else:
                likedata = UserLikes.objects.create(
                    user_id = likeinfo['profuserid'],
                    likedUser_id = loginuser_id
                )
                likedata.save()
                return JsonResponse({"success": True, "message":"Like Saved"})
        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 getuserlikes(request):
    stratsessionutil = StartFitSessionUtil()
    user = stratsessionutil.get_user_insession(request)
    likeinfo = json.loads(request.body.decode('utf-8'))
    try:
        if user != None:
            totallikesArr = []
            totallikesObj = {}
            totallikes = UserLikes.objects.filter(user_id=likeinfo['profuserid']).count()
            totallikesObj['totallikes'] = totallikes
            likes = UserLikes.objects.filter(user_id=likeinfo['profuserid'],likedUser_id = user['id']).count()
            if likes >0:
                totallikesObj['dislike'] = True
            else:
                totallikesObj['dislike'] = False
            totallikesArr.append(totallikesObj)
            return JsonResponse({"success": True, "totallikes": totallikesArr})
        else:
            totallikesArr1 = []
            totallikesObj1 = {}
            print('++++++++else',likeinfo['profuserid'])
            totallikes = UserLikes.objects.filter(user_id=likeinfo['profuserid']).count()
            print(totallikes)
            totallikesObj1['totallikes'] = totallikes
            totallikesObj1['dislike'] = True
            totallikesArr1.append(totallikesObj1)
            return JsonResponse({"success": True, "totallikes": totallikesArr1})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def statsOfUsersRegisterd(request):
    stratsessionutil = StartFitSessionUtil()
    user = stratsessionutil.get_user_insession(request)
    try:
        if user != None:
            userArr = []
            planArr = []
            userDetails = User.objects.values('id','email','date_joined').order_by('date_joined')
            for user in userDetails:
                userData = dict(user)
                userData['date_joined'] = userData['date_joined'].strftime("%Y-%m-%d")
                userArr.append(userData)
                print(userArr)
                planDetails = UserPlan.objects.filter(user_id = userData['id']).values('id','user_id','plan_id','createdDate').order_by('createdDate')
                if planDetails.exists():
                    for plan in planDetails:
                        userplans = dict(plan)
                        userplans['createdDate'] = userplans['createdDate'].strftime("%Y-%m-%d")
                        print(userplans)
                        planArr.append(userplans)
            return JsonResponse({"success": True, "UserArr": userArr,"planArr":planArr})
        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 programTypeStats(request):
    stratsessionutil = StartFitSessionUtil()
    user = stratsessionutil.get_user_insession(request)
    programTypes = json.loads(request.body.decode('utf-8'))
    try:
        if user != None:
            programArr = []
            userplanArr = []
            if programTypes['program'] == "0":
                print("in Here")
                programTypeSubs = UserPlan.objects.select_related('Plan__id','ProgramType__id').filter(plan_id__programType = 1).values("id","plan_id__programType__programTypeName",'user_id',"plan_id","plan_id__programType__id","createdDate").order_by('createdDate')
                if programTypeSubs.exists():
                    starter = len(programTypeSubs)
                else:
                    starter = "0"
                programArr.append({"plan": "Starter", "count": starter})
                programTypeSubs1 = UserPlan.objects.select_related('Plan__id','ProgramType__id').filter(plan_id__programType = 2).values("id","plan_id__programType__programTypeName",'user_id',"plan_id","plan_id__programType__id","createdDate").order_by('createdDate')
                if programTypeSubs1.exists():
                    intermediate = len(programTypeSubs1)
                else:
                    intermediate = "0"
                programArr.append({"plan": "Intermediate ", "count": intermediate})
                programTypeSubs2 = UserPlan.objects.select_related('Plan__id','ProgramType__id').filter(plan_id__programType = 3).values("id","plan_id__programType__programTypeName",'user_id',"plan_id","plan_id__programType__id","createdDate").order_by('createdDate')
                if programTypeSubs2.exists():
                    advanced = len(programTypeSubs)
                else:
                    advanced = "0"
                programArr.append({"plan": "Advanced", "count": advanced})
                return JsonResponse({"success": True, "plans": programArr})
            elif programTypes['program'] == "1":
                print("in here 2")
                planDetails = Plan.objects.select_related('ProgramType__id').filter(programType_id =1,planStatus=1,activationStatus=1).values('planName','id','createdDate').order_by('createdDate')
                if planDetails.exists():
                    for plan in planDetails:
                        planId = dict(plan)
                        userplans = UserPlan.objects.select_related('Plan__id','ProgramType__id').filter(plan_id =planId['id']).values("id","createdDate","plan_id__planName").order_by('createdDate')
                        if userplans.exists():
                            userplanArr.append({"plan":planId['planName'],"count":len(userplans)})
                        else:
                            userplanArr.append({"plan":planId['planName'],"count":0})
                    return JsonResponse({"success": True, "plans": userplanArr})
                else:
                    userplanArr.append({"plan": None, "count": 0})
                    return JsonResponse({"success": False, "plans":userplanArr})
            elif programTypes['program'] == "2":
                print("in here 3")
                planDetails = Plan.objects.select_related('ProgramType__id').filter(programType_id=2,planStatus=1,activationStatus=1).values('planName','id','createdDate').order_by('createdDate')
                if planDetails.exists():
                    for plan in planDetails:
                        planId = dict(plan)
                        userplans = UserPlan.objects.select_related('Plan__id', 'ProgramType__id').filter(plan_id=planId['id']).values("id", "createdDate", "plan_id__planName").order_by('createdDate')
                        if userplans.exists():
                            userplanArr.append({"plan": planId['planName'], "count": len(userplans)})
                        else:
                            userplanArr.append({"plan": planId['planName'], "count": 0})
                    return JsonResponse({"success": True, "plans": userplanArr})
                else:
                    userplanArr.append({"plan": None, "count": 0})
                    return JsonResponse({"success": False, "plans": userplanArr})
            elif programTypes['program'] == "3":
                print("in here 3")
                planDetails = Plan.objects.select_related('ProgramType__id').filter(programType_id=3,planStatus=1,activationStatus=1).values('planName','id','createdDate').order_by('createdDate')
                if planDetails.exists():
                    for plan in planDetails:
                        planId = dict(plan)
                        userplans = UserPlan.objects.select_related('Plan__id', 'ProgramType__id').filter(plan_id=planId['id']).values("id", "createdDate", "plan_id__planName").order_by('createdDate')
                        if userplans.exists():
                            userplanArr.append({"plan": planId['planName'], "count": len(userplans)})
                        else:
                            userplanArr.append({"plan": planId['planName'], "count": 0})
                    return JsonResponse({"success": True, "plans": userplanArr})
                else:
                    userplanArr.append({"plan": None, "count": 0})
                    return JsonResponse({"success": False, "plans": userplanArr})
        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 sessionscount(request):
    stratsessionutil = StartFitSessionUtil()
    user = stratsessionutil.get_user_insession(request)
    plandetails = json.loads(request.body.decode('utf-8'))
    try:
        if user != None:
            sessArr = []
            x= connection.cursor()
            if plandetails['level'] == "session":
                query = "SELECT count(session_id) as totalSessions, session_id, plan_id FROM `Userplan_userexercise` where plan_id ="+str(plandetails['plan_id'])+" group by session_id order by session_id desc, plan_id desc"
            else:
                query = "SELECT count(microcycle_id) as totalSessions, microcycle_id, plan_id FROM `Userplan_userexercise` where plan_id =" + str(plandetails['plan_id']) + " group by microcycle_id order by microcycle_id desc, plan_id desc"
            x.execute(query)
            resultQuery = dictfetchall(x)
            preCnt = None
            for dt in resultQuery:
                if preCnt is not None:
                    dt['totalSessions'] = dt['totalSessions'] - preCnt
                    if dt['totalSessions'] < 0:
                        dt['totalSessions'] = 0
                    sessArr.append(dt)
                    if preCnt < dt['totalSessions']:
                        preCnt = dt['totalSessions']
                else:
                    sessArr.append(dt)
                    preCnt = dt['totalSessions']
            sessArr.reverse()
            return JsonResponse({"data":sessArr})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def plannameslist(request):
    stratsessionutil = StartFitSessionUtil()
    user = stratsessionutil.get_user_insession(request)
    try:
        if user != None:
            planArr = []
            plans = Plan.objects.filter(planStatus = 1,activationStatus=1).values('id','planName')
            for plan in plans:
                planObj = dict(plan)
                planArr.append(planObj)
            return JsonResponse({"data":planArr})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def sessionCheck(request):
    stratsessionutil = StartFitSessionUtil()
    user = stratsessionutil.get_user_insession(request)
    try:
        usercountry = 190
        if user != None:
            if 'userCountry' in user:
                usercountry = user['userCountry']
            return JsonResponse({"success":True,"message":"User Logged in","userCountry":usercountry})
        else:
            return JsonResponse({"success": False, "message": "User Logged out"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"success":False,"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def gymPlanLists(request):
    stratsessionutil = StartFitSessionUtil()
    user = stratsessionutil.get_user_insession(request)
    try:
        if user != None:
            orgId = user['organization']
            try:
                planDetails = Plan.objects.select_related('Goals__id','ProgramType__id','User__id').filter(planStatus = 1,activationStatus=1,createdBy_id__organization_id = orgId).values('id', 'planName', 'planPhoto', 'price', 'planGoal__goalName', 'planDescription','programType__programTypeName','programType__id','duration_weeks','createdBy','ability','createdBy_id__avatar','createdBy_id__first_name','programType_id','createdBy_id','licencePolicy','originalPlanner_id','iosPrice','iosStatus')
                planArr = []
                planCoaches = []
                planSet = set()
                for dt in planDetails:
                    dataObj = dict(dt)
                    if dataObj['licencePolicy'] == "3" or dataObj['licencePolicy'] == "White-Label":
                        partnerName = User.objects.get(id=dataObj['createdBy_id'])
                        dataObj['planDescription'] = str(dataObj['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
                    else:
                        coachName = User.objects.get(id=dataObj['originalPlanner_id'])
                        dataObj['planDescription'] = str(dataObj['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
                    planCoaches.append(dataObj['createdBy'])
                    planSet.add(dataObj['programType_id'])
                print(planSet)
                for setId in planSet:
                    if setId ==1:
                        planList = Plan.objects.select_related('Goals__id', 'ProgramType__id', 'User__id').filter(planStatus=1,programType_id = 1,activationStatus=1,createdBy_id__organization_id = orgId).values('id', 'planName', 'planPhoto', 'price', 'planGoal__goalName','planDescription', 'programType__programTypeName', 'programType__id','duration_weeks', 'createdBy', 'ability', 'createdBy_id__avatar','createdBy_id__first_name', 'programType_id','createdBy_id','licencePolicy','originalPlanner_id','iosPrice','iosStatus').order_by('-id')[:2]
                    if setId ==2:
                        planList = Plan.objects.select_related('Goals__id', 'ProgramType__id', 'User__id').filter(planStatus=1,programType_id = 2,activationStatus=1,createdBy_id__organization_id = orgId).values('id', 'planName', 'planPhoto', 'price', 'planGoal__goalName','planDescription', 'programType__programTypeName', 'programType__id','duration_weeks', 'createdBy', 'ability', 'createdBy_id__avatar','createdBy_id__first_name', 'programType_id','createdBy_id','licencePolicy','originalPlanner_id','iosPrice','iosStatus').order_by('-id')[:2]
                    if setId ==3:
                        planList = Plan.objects.select_related('Goals__id', 'ProgramType__id', 'User__id').filter(planStatus=1,programType_id = 3,activationStatus=1,createdBy_id__organization_id = orgId).values('id', 'planName', 'planPhoto', 'price', 'planGoal__goalName','planDescription', 'programType__programTypeName', 'programType__id','duration_weeks', 'createdBy', 'ability', 'createdBy_id__avatar','createdBy_id__first_name', 'programType_id','createdBy_id','licencePolicy','originalPlanner_id','iosPrice','iosStatus').order_by('-id')[:2]
                    for plan in planList:
                        planObj = dict(plan)
                        if planObj['licencePolicy'] == "3" or planObj['licencePolicy'] == "White-Label":
                            partnerName = User.objects.get(id=planObj['createdBy_id'])
                            planObj['planDescription'] = str(planObj['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
                        else:
                            coachName = User.objects.get(id=planObj['originalPlanner_id'])
                            planObj['planDescription'] = str(planObj['planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
                        planObj['planPurpose'] =planObj['ability']
                        planObj['planType'] = planObj['programType__programTypeName']
                        planObj['planCompetency']= "0"
                        planObj['planPrice'] = planObj['price']
                        planObj['coachId'] = planObj['createdBy_id']
                        planObj['planGoal'] = planObj['planGoal__goalName']
                        planObj['planLevel'] = planObj['programType__id']
                        
                        planObj['planDuration'] = planObj['duration_weeks']
                        planObj['coachId'] = planObj['createdBy_id']
                        planArr.append(planObj)
                coachDetails = User.objects.filter(id__in = planCoaches).values()
                coachArr = []
                for coach in coachDetails:
                    coach_id = dict(coach)
                    coach_id['followers'] = '20'
                    if coach_id['avatar'] is not None:
                        coach_id['coachThumbnail'] = coach_id['avatar']
                    else:
                        coach_id['coachThumbnail'] = ''
                    coach_id['coachId'] = coach['id']
                    coach_id['coachName'] = coach['first_name'] + ' ' + coach['last_name']
                    coachPlansArr = []
                    plans = Plan.objects.filter(createdBy_id=coach_id['id']).values('id')
                    for pl in plans:
                        coachPlans = dict(pl)
                        coachPlansArr.append(coachPlans['id'])
                    coach_id['coachPlans'] = coachPlansArr
                    coachArr.append(coach_id)
                return JsonResponse({"success": True, "details": planArr,"allCoaches":coachArr})
            except Exception as e:
                logger.exception("something wrong")
                return JsonResponse({"msg": str(e)})
        else:
            return JsonResponse({"success": False, "message": "User Logged out"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"success":False,"msg": str(e)})

def insertReferalCode(request):
    userVal = User.objects.values('id')
    for uId in userVal:
        userObj = dict(uId)
        userId = userObj['id']
        randomCode1 = ''.join(choice('0123456789') for i in range(6))
        randcode1 = str(randomCode1)
        userRefralexists = UserReferral.objects.filter(user_id=userId).values()
        if userRefralexists.exists():
            message = "refral Code exists"
            print(message)
        else:
            userref = UserReferral.objects.create(
                user_id=userId,
                referralCode=randcode1,
                status=1
            )
            userref.save()
    return JsonResponse({"success": True, "message": "Referal Code Inserted"})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def createUserPlateWts(request):
    stratsessionutil = StartFitSessionUtil()
    user = stratsessionutil.get_user_insession(request)
    user_id = user['id']
    try:
        if user != None:
            wtdata = json.loads(request.body.decode('utf-8'))
            if 'wtinfo' in wtdata:
                for dt in wtdata['wtinfo']:
                    print(dt)
                    if ('weight' in dt and dt['weight']!= '' and dt['weight'] != 0):
                        getwts = UserPlateWeight.objects.values('id','user_id','weight','count','barbell','status','index').filter(user_id = user_id,barbell=dt['barbell'],index=dt['index'])
                        if getwts.exists():
                            print('---------exists-------')
                            for dt1 in getwts:
                                if ('checked' in dt and dt['checked'] == True):
                                    upwts = UserPlateWeight.objects.get(id = dt1['id'])
                                    upwts.weight = dt['weight']
                                    upwts.count = dt['count']
                                    upwts.barbell = dt['barbell']
                                    upwts.index = dt['index']
                                    upwts.status = 1
                                    upwts.save()
                                else:
                                    upwts = UserPlateWeight.objects.get(id=dt1['id'])
                                    upwts.weight = dt['weight']
                                    upwts.count = dt['count']
                                    upwts.barbell = dt['barbell']
                                    upwts.index = dt['index']
                                    upwts.status = 0
                                    upwts.save()
                        else:
                            if ('checked' in dt and dt['checked'] == True):
                                print('---------create-----------')
                                wtinf = UserPlateWeight.objects.create(
                                    user_id =  user_id,
                                    weight = dt['weight'],
                                    count = dt['count'],
                                    barbell = dt['barbell'],
                                    index = dt['index'],
                                    status = 1
                                )
                                wtinf.save()
                getplatewtArr=[]
                getplatewts = UserPlateWeight.objects.all().filter(user_id=user_id, status =1)
                for pdata in getplatewts:
                    pObj = model_to_dict(pdata)
                    if (pObj['status'] == 1):
                        pObj['checked'] = True
                    if (pObj['status'] == 0):
                        pObj['checked'] = False
                    getplatewtArr.append(pObj)
                return JsonResponse({"success": True, "message": "Plate weights saved successfully","plateWts":getplatewtArr})
            else:
                return JsonResponse({"success": False, "message": "Something went wrong"})
        else:
            return JsonResponse({"success": False, "message": "User Logged out"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"success":False,"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def getPlateWeights(request):
    stratsessionutil = StartFitSessionUtil()
    user = stratsessionutil.get_user_insession(request)
    user_id = user['id']
    try:
        if user != None:
            getplatewtArr = []
            getBarbelArr = []
            getplatewts = UserPlateWeight.objects.all().filter(user_id=user_id, status =1)
            for pdata in getplatewts:
                pObj = model_to_dict(pdata)
                if(pObj['status'] ==1):
                    pObj['checked'] =True
                if (pObj['status'] == 0):
                    pObj['checked'] = False
                if(pObj['barbell'] == 0):
                    getplatewtArr.append(pObj)
                if (pObj['barbell'] == 1):
                    getBarbelArr.append(pObj)
            return JsonResponse({"success": True, "plateWts": getplatewtArr, "barbelWts":getBarbelArr})
        else:
            return JsonResponse({"success": False, "message": "User Logged out"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"success":False,"msg": str(e)})

def createPlateWeights(request):
    platesArr = [50,30,20,15,10,7.5,5,2.5,1]
    barbellArr = [10,15,20]
    activeUsers = UserPlan.objects.filter(status__in=[1,3]).values('user_id')
    for val in activeUsers:
        userObj = dict(val)
        userId = userObj['user_id']
        extigwts = UserPlateWeight.objects.filter(user_id = userId).values()
        if extigwts.exists():
            print("value Already eXists")
        else:
            idx = -1
            idx1 = -1
            for wt in platesArr:
                idx = idx + 1
                wtinf = UserPlateWeight.objects.create(
                    user_id=userId,
                    weight=wt,
                    count=4,
                    barbell=0,
                    index=idx,
                    status=1
                )
                wtinf.save()
            for val in barbellArr:
                idx1 = idx1 + 1
                wtinf = UserPlateWeight.objects.create(
                    user_id=userId,
                    weight=val,
                    count=1,
                    barbell=1,
                    index=idx1,
                    status=1
                )
                wtinf.save()
    return JsonResponse({"success":True,"message":"Plate weights inserted successfully"})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def getCampUrls(request):
    stratsessionutil = StartFitSessionUtil()
    user = stratsessionutil.get_user_insession(request)
    requestJson = json.loads(request.body.decode('utf-8'))
    if 'campId' in requestJson and requestJson['campId'] != '':
        campaignId = requestJson['campId']
    try:
        checkUrl = CampainUrls.objects.filter(campaignSource = requestJson['campaignSource'],campaignName = requestJson['campaignName']).values()
        if checkUrl.exists():
            for val in checkUrl:
                valObj = dict(val)
                campId = valObj['id']
            campvalues = CampaignDetails.objects.filter(campaign_id = campId).values()
            if user != None:
                userId = user['id']
                usercampVal = CampaignDetails.objects.filter(campaign_id = campId,user_id=userId).values()
                if usercampVal.exists():
                    updateCamp = CampaignDetails.objects.get(id=campaignId)
                    updateCamp.user_id = userId
                    updateCamp.save()
                else:
                    campdetails = CampaignDetails.objects.create(
                        user_id=userId,
                        campaign_id = campId
                    )
                    campdetails.save()
                return JsonResponse({"success": True, "message": "Campaign Details Saved Succesfully"})

            else:
                campdetails = CampaignDetails.objects.create(
                    campaign_id=campId
                )
                campdetails.save()
                return JsonResponse({"success": False, "message": "User Logged out","campId":campdetails.id})
        else:
            return JsonResponse({"success": False, "message": "Invalid Campiagn Details"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"success":False,"msg": str(e)})

def rupeeConversion(request):
    #requestJson = json.loads(request.body.decode('utf-8'))
    currencyValues = PriceConversion.objects.get(id=1)
    #inrPrice = float(requestJson['price'])*currencyValues.inrValue
    return JsonResponse({"success": True, "inrPrice": currencyValues.inrValue})

def updateFitnessDetails(request):
    users = User.objects.values()
    for user in users:
        userObj = dict(user)
        uId = userObj['id']
        userPlanDetails = UserPlan.objects.filter(user_id = uId).last()
        if userPlanDetails:
            planId = userPlanDetails.plan_id
            planVal = Plan.objects.get(pk=planId)
            if planVal.programType_id == 1:
                trainerLevel = 2
            elif planVal.programType_id == 2:
                trainerLevel = 3
            elif planVal.programType_id == 3:
                trainerLevel = 4
            updateFitnessVal = FitnessProfile.objects.filter(user_id = uId).last()
            if updateFitnessVal:
                fitnessId = updateFitnessVal.id
                updatefitness = FitnessProfile.objects.get(pk = fitnessId)
                updatefitness.trainingLevel = trainerLevel
                updatefitness.save()
    return JsonResponse({"success":True})

def planNames(request):
    arr = []
    planNameVal = Plan.objects.filter(planStatus = 1,activationStatus=1).values('id','planName')
    for val in planNameVal:
        valObj = dict(val)
        arr.append(valObj)
    return JsonResponse({"success": True,"data":arr})

def analyticsData(request):
    requestJson = json.loads(request.body.decode('utf-8'))
    dateArr = []
    countArr = []
    x=connection.cursor()
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="List.csv"'
    if requestJson['query'] == "1":
        query = " SELECT  updatedDate, COUNT(DISTINCT ID) AS NumUsers FROM  `Subscriber_user` WHERE updatedDate BETWEEN ' "+requestJson['startDate']+" ' AND ' "+requestJson['endDate']+" ' GROUP BY CONCAT(MONTH(`updatedDate`), YEAR(`updatedDate`),DATE(`updatedDate`) ) ORDER BY updatedDate ASC "
        print(query,"---------")
    elif requestJson['query'] == "2":
        query = " SELECT  updatedDate, COUNT(DISTINCT ID) AS NumUsers FROM  `Subscriber_user` WHERE updatedDate BETWEEN ' "+requestJson['startDate']+" ' AND ' "+requestJson['endDate']+" ' GROUP BY CONCAT(MONTH(`updatedDate`), YEAR(`updatedDate`) ) ORDER BY updatedDate ASC "
    elif requestJson['query'] == "3":
        query = " SELECT  updatedDate, COUNT(DISTINCT user_id) AS NumUsers FROM  `Userplan_userplan` WHERE updatedDate BETWEEN ' " +requestJson['startDate'] + " ' AND ' " + requestJson['endDate'] + " ' GROUP BY CONCAT(MONTH(`updatedDate`), YEAR(`updatedDate`),DATE(`updatedDate`) ) ORDER BY updatedDate ASC "
    elif requestJson['query'] == "4":
        query = " SELECT  updatedDate, COUNT(DISTINCT user_id) AS NumUsers FROM  `Userplan_userplan` WHERE updatedDate BETWEEN ' " +requestJson['startDate'] + " ' AND ' " + requestJson['endDate'] + " ' GROUP BY CONCAT(MONTH(`updatedDate`), YEAR(`updatedDate`) ) ORDER BY updatedDate ASC "
    elif requestJson['query'] == "5":
        query = " SELECT  updatedDate, COUNT(DISTINCT user_id) AS NumUsers FROM  `Userplan_userplan` WHERE updatedDate BETWEEN ' " +requestJson['startDate'] + " ' AND ' " + requestJson['endDate'] + " ' AND plan_id = "+requestJson['planId']+" GROUP BY CONCAT(MONTH(`updatedDate`), YEAR(`updatedDate`),DATE(`updatedDate`) ) ORDER BY updatedDate ASC "
    elif requestJson['query'] == "6":
        query = " SELECT  updatedDate, COUNT(DISTINCT user_id) AS NumUsers FROM  `Userplan_userplan` WHERE updatedDate BETWEEN ' " +requestJson['startDate'] + " ' AND ' " + requestJson['endDate'] + " ' GROUP BY CONCAT(MONTH(`updatedDate`), YEAR(`updatedDate`) ) ORDER BY updatedDate ASC "
    else:
        query = ''
    x.execute(query)
    resultQuery = dictfetchall(x)
    print(resultQuery,"----------------------")
    writer = csv.writer(response)
    writer.writerow(['Updated Date','Num of Users'])
    for val in resultQuery:
        valObj = dict(val)
        writer.writerow([valObj['updatedDate'].strftime("%Y-%m-%d"),valObj['NumUsers']])
        dateArr.append(valObj['updatedDate'].strftime("%Y-%m-%d"))
        countArr.append(valObj['NumUsers'])
    if 'querySet' in requestJson and requestJson['querySet'] == "10":
        return response
    return JsonResponse({"success": True, "dateArr": dateArr,"count":countArr})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def celebInvites(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    emailslist = json.loads(request.body.decode('utf-8'))
    req = emailslist
    url = "subscriber/celebInvites/"
    try:
        if username != None:
            #print(emailslist,"12456789")
            #email = emailslist['emails'].split(',')
            #for value in email:
            randomCode = ''.join(choice('0123456789') for i in range(6))
            #print(randomCode)
            rand = str(randomCode)
            secret_code_plain = emailslist['email'] + '#' + str(randomCode)
            secret_code_encode = base64.b64encode(secret_code_plain.encode('ascii'))
            existingInvites = Invitations.objects.filter(email = emailslist['email'],userType = 8)
            existingUser = User.objects.filter(email = emailslist['email'])
            if existingUser.exists():
                return JsonResponse({"success": True, "message": "Invitation with this mail-id already accepted or already a user in StratFit"})
            elif 'status' in emailslist !='' or 'status' in emailslist !=None:
                validateLink = request.META['HTTP_HOST']
                link = "http://"+validateLink+"#/acceptinvites/" + secret_code_encode.decode("utf-8")
                subject = "Invitation"
                to_email = emailslist['email']
                ctx = {
                    'first_name': emailslist['name'],
                    'link': link
                }
                message = render_to_string('coachinvitations.html', ctx)
                officeMail(subject, message, to_email)
                return JsonResponse({"success": True, "message": "Invitation sent successfully", })
            elif existingInvites.exists():
                return  JsonResponse({"success":True,"message":"Invitation to this email-id already sent"})
            else:
                createInvitaion = Invitations.objects.create(
                    name = emailslist['name'],
                    email = emailslist['email'],
                    secretCode = secret_code_encode,
                    userType = 8
                )
                createInvitaion.save()
                validateLink = request.META['HTTP_HOST']
                link = "http://"+validateLink+"/#/acceptinvites/"+secret_code_encode.decode("utf-8")
                subject = "Invitation"
                to_email = emailslist['email']
                ctx={
                    'first_name':emailslist['name'],
                    'link':link
                }
                message = render_to_string('coachinvitations.html',ctx)
                officeMail(subject, message, to_email)
                return JsonResponse({"success": True, "message": "Invitation sent successfully",})
        else:
            return JsonResponse({"success": False, "message": "user logged out",})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg":str(e)})


@never_cache
def fitbitauth(request):
    requestJson = str(request)
    requestVal = requestJson.split("?")[1][:-2]
    code = requestVal.split("=")[1]
    return JsonResponse({"success": True, "message": code})

@api_view(['GET', 'POST'])
@never_cache
def news_letter(request):    
    data=request.data
    print(data)
    try:
        vemail=data['email']
        if vemail !=None:
                user=News_letter.objects.filter(news_letter_email=vemail)
                if user.exists():
                    return JsonResponse({"success":False,"message":"user with this email exists"})
                else:
                    user1=User.objects.filter(email=vemail)
                    if user1.exists():
                        return JsonResponse({"success":False,"message":"user with this Email Exists"})
                    else:
                        news_email=News_letter(news_letter_email=vemail)
                        news_email.save()
                        return JsonResponse({"success":True,"message":"your email is successfully saved"})  
        else:
            return JsonResponse({"success":False,"message":"please enter valid credentials"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg":str(e)})




