import json

from datetime import time, datetime
from django.contrib.auth.models import Permission
from django.core.mail import EmailMultiAlternatives
from django.forms import model_to_dict
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.db import IntegrityError, connection
# Create your views here.
from django.template.loader import render_to_string
from django.views.decorators.cache import never_cache
try: # for pip >= 10
    from pip._internal.req.req_install import logger
except ImportError: # for pip <= 9.0.3
    from pip.req.req_install import logger

from rest_framework.decorators import api_view, authentication_classes

from Plan.models import MetabolicValues
from Subscriber.views import exceptionMail
from Subscriber.Authentication import SessionAuthentication, IsAuthenticated, StartFitSessionUtil
from Subscriber.models import User
from Subscriber.views import dictfetchall
from utility.models import  ExerciseType, NewExercise,Exercise, Videos, ExcerciseTypeVideos, ExcerciseVideos, ProgramType, Goals, InolRange, Country, State,ExerciseCategory, AdvExercises
import csv
import json
from stratadmin.models import Admin

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def makeAdmin(request):
    #user = request.session['user_id']
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    data = json.loads(request.body.decode('utf-8'))
    user = username['id']
    req=data
    url="stratadmin/makeAdmin"
    try:
        if username != None:
            print(data,"in Here")
            for dt in data:
                print(dt,"--<>--")
                useradmin = User.objects.get(pk = dt)
                useradmin.is_superuser = 1
                useradmin.save()
                userDetails = User.objects.filter(id = dt).values('id','email','first_name','is_superuser','middle_name','last_name','username','is_active','password')
                if userDetails.exists():
                    for dt1 in userDetails:
                        dataObj = dict(dt1)
                        if dataObj['is_superuser'] == 1:
                            adminDetails = Admin.objects.create(
                                email = dataObj['email'],
                                first_name = dataObj['first_name'],
                                middle_name = dataObj['middle_name'],
                                last_name = dataObj['last_name'],
                                username = dataObj['username'],
                                is_active = dataObj['is_active'],
                                password = dataObj['password'],
                                createdBy_id  = user,
                                updatedBy_id = user
                            )
                            adminDetails.save()
            return JsonResponse({"success":True,"message":"Admin Created Successfully"})
        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)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def createExerciseType(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    exinfo = json.loads(request.body.decode('utf-8'))
    user = username['id']
    req = exinfo
    url="stratadmin/addExerciseType/"
    try:
        if username != None:
            if 'id' in exinfo:
                details = ExerciseType.objects.get(id=exinfo['id'])
                print(details)
                details.exerciseTypeName = exinfo['exerciseTypeName']
                details.exerciseTypeCode=exinfo['exerciseTypeCode']
                details.exerciseTypeStatus=exinfo['exerciseTypeStatus']
                details.exerciseTypeDesc=exinfo['exerciseTypeDesc']
                details.equipment=exinfo['equipment']
                details.exerciseCategory_id = exinfo['exerciseCategory']
                details.save()
                return JsonResponse({"success":True,"message":"ExerciseType Updated Successfully"})
            else:
                if ExerciseType.objects.filter(exerciseTypeName=exinfo['exerciseTypeName'],exerciseCategory=exinfo['exerciseCategory']).exists():
                    return JsonResponse({"success": False, "message": 'exerciseTypeName already exists'})

                exTypes = ExerciseType.objects.create(
                    exerciseTypeName = exinfo['exerciseTypeName'],
                    exerciseTypeCode=exinfo['exerciseTypeCode'],
                    exerciseTypeStatus=exinfo['exerciseTypeStatus'],
                    exerciseTypeDesc=exinfo['exerciseTypeDesc'],
                    equipment=exinfo['equipment'],
                    exerciseCategory_id = exinfo['exerciseCategory'],
                    createdBy_id=user,
                    modifiedBy_id=user
                )
                exTypes.save()
                return JsonResponse({"success":True,"message":"ExerciseType 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 getExerciseType(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    print(username)
    user = username['id']
    req = "GET"
    url = "stratadmin/getExerciseType/"
    try:
        #user = username['id']
        #print(user)
        if username != None:
            if 'rows' in request.POST and request.POST['rows'] != '':
                rows = int(request.POST['rows'])
            else:
                rows = 50

            if 'page' in request.POST and request.POST['page'] != '':
                page = int(request.POST['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            userpage = ExerciseType.objects.values('id','exerciseCategory_id','exerciseTypeName','exerciseTypeCode','exerciseTypeStatus','exerciseTypeDesc','equipment','exerciseCategory__categoryName','createdBy','modifiedBy','createdDate','modifiedDate').order_by('-createdDate')
            userarry = []
            total = len(userpage)
            data = userpage[offset:tot]
            for dt in data:
                #print(dt)
                dataObj = dict(dt)
                print(dataObj)
                userarry.append(dataObj )
            return JsonResponse({"success": True, "details": userarry,"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 exerciseTypeSearch(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    exeinfo = json.loads(request.body.decode('utf-8'))
    req = exeinfo
    url = "stratadmin/exerciseTypeSearch/"
    try:
        if username != None:
            print(exeinfo)
            if 'rows' in exeinfo and 'rows' != '':
                rows = int(exeinfo['rows'])
            else:
                rows = 50
            if 'page' in exeinfo and 'page' != '':
                page = int(exeinfo['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            #excfilter = ExerciseType.objects.all().order_by('-modifiedDate')
            excfilter =ExerciseType.objects.values('id','exerciseCategory_id','exerciseTypeName','exerciseTypeCode','exerciseTypeStatus','exerciseTypeDesc','equipment','exerciseCategory__categoryName','createdBy','modifiedBy','createdDate','modifiedDate').order_by('-modifiedDate')
            #print(exeinfo['excdata']['exerciseCategory'],'+++++++++++++')
            if 'excdata' in exeinfo !='':
                if 'exerciseCategory' in exeinfo['excdata']  and exeinfo['excdata']['exerciseCategory'] !='':
                    excfilter = excfilter.filter(exerciseCategory_id = exeinfo['excdata']['exerciseCategory'])
                if 'exTypeName' in exeinfo['excdata']  and exeinfo['excdata']['exTypeName'] !='':
                    excfilter = excfilter.filter(exerciseTypeName__icontains = exeinfo['excdata']['exTypeName'])
                if 'exTypeCode' in exeinfo['excdata']  and exeinfo['excdata']['exTypeCode'] !='':
                    excfilter = excfilter.filter(exerciseTypeCode__icontains = exeinfo['excdata']['exTypeCode'])
                if 'equipment' in exeinfo['excdata']  and exeinfo['excdata']['equipment'] !='':
                    excfilter = excfilter.filter(equipment__icontains = exeinfo['excdata']['equipment'])
                if 'exerciseTypeStatus' in exeinfo['excdata']  and exeinfo['excdata']['exerciseTypeStatus'] !='':
                    excfilter = excfilter.filter(exerciseTypeStatus = exeinfo['excdata']['exerciseTypeStatus'])
            dataArr = list()
            total = len(excfilter)
            totaldata = excfilter[offset:tot]
            for dt in totaldata:
                dataObj = dict(dt)
                dataArr.append(dataObj)
                print(dataArr)
            return JsonResponse({"success": True, "details": dataArr,"total":total})
        else:
            return JsonResponse({"success": False,"message":"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 createExercise(request):
    #user = request.session['user_id']
    #print(user)
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    exinfo = json.loads(request.body.decode('utf-8'))
    req = exinfo
    url = "stratadmin/addExercise/"
    try:
        if username != None:
            if 'id' in exinfo and exinfo['id'] != None:
                exercisesInfo = Exercise.objects.get(pk = exinfo['id'])
                exercisesInfo.exerciseName = exinfo['exerciseName']
                exercisesInfo.exerciseDesc = exinfo['exerciseDesc']
                exercisesInfo.exerciseStatus = exinfo['exerciseStatus']
                exercisesInfo.modifiedBy_id = user
                if 'equipment' in exinfo and exinfo['equipment'] != None:
                    exercisesInfo.equipment = exinfo['equipment']
                if 'preExInstructions' in exinfo and exinfo['preExInstructions'] != None:
                    exercisesInfo.preExInstructions = exinfo['preExInstructions']
                if 'postExInstructions' in exinfo and exinfo['postExInstructions'] != None:
                    exercisesInfo.postExInstructions = exinfo['postExInstructions']
                if 'distanceExists' in exinfo and exinfo['distanceExists'] != None:
                    exercisesInfo.distanceExists = exinfo['distanceExists']
                if 'timeExists' in exinfo and exinfo['timeExists'] != None:
                    exercisesInfo.timeExists = exinfo['timeExists']
                if 'exAbilities' in exinfo and exinfo['exAbilities'] != None:
                    exercisesInfo.exAbilities = exinfo['exAbilities']
                if 'repsExists' in exinfo and exinfo['repsExists'] != None:
                    exercisesInfo.repsExists = exinfo['repsExists']
                if 'weightExists' in exinfo and exinfo['weightExists'] != None:
                    exercisesInfo.weightExists = exinfo['weightExists']
                if 'setInstructions' in exinfo and exinfo['setInstructions'] != None:
                    exercisesInfo.setInstructions = exinfo['setInstructions']
                if 'speedExists' in exinfo and exinfo['speedExists'] != None:
                    exercisesInfo.speedExists=exinfo['speedExists']
                if 'heightExists' in exinfo and exinfo['heightExists'] != None:
                    exercisesInfo.heightExists=exinfo['heightExists']
                if 'setInstContent' in exinfo and exinfo['setInstContent'] != None:
                    exercisesInfo.setInstructions=exinfo['setInstContent']
                if 'timeShortest' in exinfo and exinfo['timeShortest'] != None:
                    exercisesInfo.timeShortest=exinfo['timeShortest']
                if 'youtubeUrl' in exinfo and exinfo['youtubeUrl'] !=0 and exinfo['youtubeUrl'] !='0' and exinfo['youtubeUrl'] !=False:
                    if 'video_id__videoLink' in exinfo and exinfo['video_id__videoLink'] != None:
                        if len(exinfo['video_id__videoLink'].split('=')) >1:
                            url = exinfo['video_id__videoLink'].split('=')[1]
                        else:
                            url = exinfo['video_id__videoLink'].split('=')[0]
                        videoLink = Videos.objects.get(id = exercisesInfo.video_id)
                        videoLink.videoLink = url
                        videoLink.save()
                else:
                    if 'videoLink' in exinfo and exinfo['videoLink'] != None:
                        videoLink = Videos.objects.get(id = exercisesInfo.video_id)
                        videoLink.videoLink = exinfo['videoLink']
                        videoLink.save()
                exercisesInfo.save()
                '''
                createAdvEx = AdvExercises.objects.get(exercise_id = exercisesInfo.id)
                if createAdvEx:
                    if 'exType' in exinfo and exinfo['exType'] != '' and exinfo['exType'] !=None:
                        if exinfo['exType'] == "1":
                            createAdvEx.complexActivity = True
                            createAdvEx.straightActivity = False
                        else:
                            createAdvEx.straightActivity = True
                            createAdvEx.complexActivity = False
                            createAdvEx.complexMethod = ''
                            createAdvEx.complexInstructions = ''
                            createAdvEx.complexRecords = 0
                    if 'tmax' in exinfo and exinfo['tmax'] != '' and exinfo['tmax'] != None:
                        if 'weight' in exinfo['tmax'] and exinfo['tmax']['weight'] != '' and exinfo['tmax']['weight'] != None:
                            createAdvEx.maxWeight = exinfo['tmax']['weight']
                        if 'reps' in exinfo['tmax'] and exinfo['tmax']['reps'] != '' and exinfo['tmax']['reps'] != None:
                            createAdvEx.maxReps = exinfo['tmax']['reps']
                        if 'time' in exinfo['tmax'] and exinfo['tmax']['time'] != '' and exinfo['tmax']['time'] != None:
                            createAdvEx.maxTime = exinfo['tmax']['time']
                        if 'distance' in exinfo['tmax'] and exinfo['tmax']['distance'] != '' and exinfo['tmax']['distance'] != None:
                            createAdvEx.maxDistance = exinfo['tmax']['distance']
                        if 'speed' in exinfo['tmax'] and exinfo['tmax']['speed'] != '' and exinfo['tmax']['speed'] != None:
                            createAdvEx.maxSpeed = exinfo['tmax']['speed']
                        if 'height' in exinfo['tmax'] and exinfo['tmax']['height'] != '' and exinfo['tmax']['height'] != None:
                            createAdvEx.maxHeight = exinfo['tmax']['height']
                    if 'tmaxPercent' in exinfo and exinfo['tmaxPercent'] != '' and exinfo['tmaxPercent'] != None:
                        #createAdvEx.maxHeight = exinfo['tmax']['height']
                        exercisesInfo.derivedFormula = int(exinfo['tmaxPercent'])/100
                        exercisesInfo.save()
                    if 'tmaxWeight' in exinfo and exinfo['tmaxWeight'] != '' and exinfo['tmaxWeight'] != None:
                        createAdvEx.tmaxWeight = exinfo['tmaxWeight']
                    if 'tmaxReps' in exinfo and exinfo['tmaxReps'] != '' and exinfo['tmaxReps'] != None:
                        createAdvEx.tmaxReps = exinfo['tmaxReps']
                    if 'tmaxDistance' in exinfo and exinfo['tmaxDistance'] != '' and exinfo['tmaxDistance'] != None:
                        createAdvEx.tmaxDistance = exinfo['tmaxDistance']
                    if 'tmaxTime' in exinfo and exinfo['tmaxTime'] != '' and exinfo['tmaxTime'] != None:
                        createAdvEx.tmaxTime = exinfo['tmaxTime']
                    if 'tmaxSpeed' in exinfo and exinfo['tmaxSpeed'] != '' and exinfo['tmaxSpeed'] != None:
                        createAdvEx.tmaxSpeed = exinfo['tmaxSpeed']
                    if 'tmaxHeight' in exinfo and exinfo['tmaxHeight'] != '' and exinfo['tmaxHeight'] != None:
                        createAdvEx.tmaxHeight = exinfo['tmaxHeight']
                    if 'type' in exinfo and exinfo['type'] != '' and exinfo['type'] != None:
                        createAdvEx.complexMethod = exinfo['type']['exMethod']
                        createAdvEx.complexInstructions = exinfo['type']['exInst']
                        createAdvEx.complexRounds = exinfo['type']['exRounds']
                    if 'purpose' in exinfo and exinfo['purpose'] != '' and exinfo['purpose'] != None:
                        createAdvEx.exPurpose = exinfo['purpose']
                    if 'parentExId' in exinfo and exinfo['parentExId'] != '' and exinfo['parentExId'] != None:
                        exercisesInfo.derivedFrom = exinfo['parentExId']
                        exercisesInfo.save()
                    if 'tmaxTestInst' in exinfo and exinfo['tmaxTestInst'] != '' and exinfo['tmaxTestInst'] != None:
                        createAdvEx.tmaxTestInst = exinfo['tmaxTestInst']
                    createAdvEx.save()
                    '''
        
                if 'rmMetValues' in exinfo and exinfo['rmMetValues'] !=None:
                    for metid in exinfo['rmMetValues']:
                        deletemetValues = MetabolicValues.objects.get(pk = metid)
                        deletemetValues.delete()
                if 'metValues' in exinfo and exinfo['metValues'] !=None and exinfo['metValues'] !=[]:
                    for val in exinfo['metValues']['ranges']:
                        if 'id' in val and val['id'] != None:
                            updatemetaVal = MetabolicValues.objects.get(pk = val['id'])
                            updatemetaVal.parameter = exinfo['metValues']['key']
                            updatemetaVal.exercise_id = exercisesInfo.id
                            updatemetaVal.minValue = val['min']
                            updatemetaVal.maxValue = val['max']
                            updatemetaVal.metaValue = val['value']
                            updatemetaVal.save()
                            print('update')
                        else:
                            createMetaValues =MetabolicValues.objects.create(
                                exercise_id =exercisesInfo.id,
                                parameter = exinfo['metValues']['key'],
                                minValue = val['min'],
                                maxValue = val['max'],
                                metaValue = val['value']
                            )
                            createMetaValues.save()
                return JsonResponse({"success": True, "message": "Exercise Updated Successfully", "exId": exercisesInfo.id})
            else:
                if Exercise.objects.filter(exerciseName=exinfo['exerciseName']).exists():
                    return JsonResponse({"success": False, "message": 'Exercise Name already exists'})
                else:
                    exercises = Exercise.objects.create(
                        exerciseName = exinfo['exerciseName'],
                        exerciseDesc=exinfo['exerciseDesc'],
                        exerciseStatus = exinfo['exerciseStatus'],
                        createdBy_id=user,
                        modifiedBy_id=user,
                        accessLevel = 1
                    )
                    if 'equipment' in exinfo and exinfo['equipment'] != None:
                        exercises.equipment=exinfo['equipment']
                    if 'preExInstructions' in exinfo and exinfo['preExInstructions'] != None:
                        exercises.preExInstructions=exinfo['preExInstructions']
                    if 'postExInstructions' in exinfo and exinfo['postExInstructions'] != None:
                        exercises.postExInstructions=exinfo['postExInstructions']
                    if 'distanceExists' in exinfo and exinfo['distanceExists'] != None:
                        exercises.distanceExists=exinfo['distanceExists']
                    if 'timeExists' in exinfo and exinfo['timeExists'] != None:
                        exercises.timeExists=exinfo['timeExists']
                    if 'exAbilities' in exinfo and exinfo['exAbilities'] != None:
                        exercises.exAbilities=exinfo['exAbilities']
                    if 'repsExists' in exinfo and exinfo['repsExists'] != None:
                        exercises.repsExists=exinfo['repsExists']
                    if 'weightExists' in exinfo and exinfo['weightExists'] != None:
                        exercises.weightExists=exinfo['weightExists']
                    if 'speedExists' in exinfo and exinfo['speedExists'] != None:
                        exercises.speedExists=exinfo['speedExists']
                    if 'heightExists' in exinfo and exinfo['heightExists'] != None:
                        exercises.heightExists=exinfo['heightExists']
                    if 'setInstContent' in exinfo and exinfo['setInstContent'] != None:
                        exercises.setInstructions=exinfo['setInstContent']
                    if 'timeShortest' in exinfo and exinfo['timeShortest'] != None:
                        exercises.timeShortest=exinfo['timeShortest']
                    exercises.save()
                    
                    '''
                    createAdvEx = AdvExercises.objects.create(exercise_id=exercises.id)
                    if 'exType' in exinfo and exinfo['exType'] != '' and exinfo['exType'] != None:
                        if exinfo['exType'] == "1":
                            createAdvEx.complexActivity = True
                            createAdvEx.straightActivity = False
                        else:
                            createAdvEx.straightActivity = True
                            createAdvEx.complexActivity = False
                    if 'tmax' in exinfo and exinfo['tmax'] != '' and exinfo['tmax'] != None:
                        if 'weight' in exinfo['tmax'] and exinfo['tmax']['weight'] != '' and exinfo['tmax']['weight'] != None:
                            createAdvEx.maxWeight = exinfo['tmax']['weight']
                        if 'reps' in exinfo['tmax'] and exinfo['tmax']['reps'] != '' and exinfo['tmax']['reps'] != None:
                            createAdvEx.maxReps = exinfo['tmax']['reps']
                        if 'time' in exinfo['tmax'] and exinfo['tmax']['time'] != '' and exinfo['tmax']['time'] != None:
                            createAdvEx.maxTime = exinfo['tmax']['time']
                        if 'distance' in exinfo['tmax'] and exinfo['tmax']['distance'] != '' and exinfo['tmax']['distance'] != None:
                            createAdvEx.maxDistance = exinfo['tmax']['distance']
                        if 'speed' in exinfo['tmax'] and exinfo['tmax']['speed'] != '' and exinfo['tmax']['speed'] != None:
                            createAdvEx.maxSpeed = exinfo['tmax']['speed']
                        if 'height' in exinfo['tmax'] and exinfo['tmax']['height'] != '' and exinfo['tmax']['height'] != None:
                            createAdvEx.maxHeight = exinfo['tmax']['height']
                    if 'tmaxPercent' in exinfo and exinfo['tmaxPercent'] != '' and exinfo['tmaxPercent'] != None:
                        #createAdvEx.maxHeight = exinfo['tmax']['height']
                        exercises.derivedFormula = int(exinfo['tmaxPercent'])/100
                        exercises.save()
                    if 'tmaxWeight' in exinfo and exinfo['tmaxWeight'] != '' and exinfo['tmaxWeight'] != None:
                        createAdvEx.tmaxWeight = exinfo['tmaxWeight']
                    if 'tmaxReps' in exinfo and exinfo['tmaxReps'] != '' and exinfo['tmaxReps'] != None:
                        createAdvEx.tmaxReps = exinfo['tmaxReps']
                    if 'tmaxDistance' in exinfo and exinfo['tmaxDistance'] != '' and exinfo['tmaxDistance'] != None:
                        createAdvEx.tmaxDistance = exinfo['tmaxDistance']
                    if 'tmaxTime' in exinfo and exinfo['tmaxTime'] != '' and exinfo['tmaxTime'] != None:
                        createAdvEx.tmaxTime = exinfo['tmaxTime']
                    if 'tmaxSpeed' in exinfo and exinfo['tmaxSpeed'] != '' and exinfo['tmaxSpeed'] != None:
                        createAdvEx.tmaxSpeed = exinfo['tmaxSpeed']
                    if 'tmaxHeight' in exinfo and exinfo['tmaxHeight'] != '' and exinfo['tmaxHeight'] != None:
                        createAdvEx.tmaxHeight = exinfo['tmaxHeight']
                    if 'type' in exinfo and exinfo['type'] != '' and exinfo['type'] != None:
                        createAdvEx.complexMethod = exinfo['type']['exMethod']
                        createAdvEx.complexInstructions = exinfo['type']['exInst']
                        createAdvEx.complexRounds = exinfo['type']['exRounds']
                    if 'purpose' in exinfo and exinfo['purpose'] != '' and exinfo['purpose'] != None:
                        createAdvEx.exPurpose = exinfo['purpose']
                    if 'parentExId' in exinfo and exinfo['parentExId'] != '' and exinfo['parentExId'] != None:
                        exercises.derivedFrom = exinfo['parentExId']
                        exercises.save()
                    if 'tmaxTestInst' in exinfo and exinfo['tmaxTestInst'] != '' and exinfo['tmaxTestInst'] != None:
                        createAdvEx.tmaxTestInst = exinfo['tmaxTestInst']
                    createAdvEx.save()
                    '''
                    if 'video_id__videoLink' in exinfo and exinfo['video_id__videoLink'] != '' and exinfo['video_id__videoLink'] != None:
                        if len(exinfo['video_id__videoLink'].split('=')) >1:
                            url = exinfo['video_id__videoLink'].split('=')[1]
                        else:
                            url = exinfo['video_id__videoLink'].split('=')[0]
                        videoLink = Videos.objects.create(
                            videoLink = url,
                            createdBy_id=user,
                            modifiedBy_id=user
                        )
                        videoLink.save()
                        exVideos = ExcerciseVideos.objects.create(
                            excercise_id = exercises.id,
                            video_id = videoLink.id,
                            createdBy_id=user,
                            modifiedBy_id=user
                        )
                        exVideos.save()
                        exercises.video_id = videoLink.id
                    if 'videoUrl' in exinfo and exinfo['videoUrl'] != '' and exinfo['videoUrl'] != None:
                        videoLink = Videos.objects.create(
                            videoLink = exinfo['videoUrl'],
                            createdBy_id=user,
                            modifiedBy_id=user,
                            youtubeUrl = False
                        )
                        videoLink.save()
                        exVideos = ExcerciseVideos.objects.create(
                            excercise_id = exercises.id,
                            video_id = videoLink.id,
                            createdBy_id=user,
                            modifiedBy_id=user
                        )
                        exVideos.save()
                        exercises.video_id = videoLink.id
                    exercises.save()
                    return JsonResponse({"success":True,"message":"Exercise Saved Successfully","exId":exercises.id})
        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 createExercise1(request):
    #user = request.session['user_id']
    #print(user)
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    exinfo = json.loads(request.body.decode('utf-8'))
    req = exinfo
    url = "stratadmin/addExercisev2/"
    try:
        if username != None:
            if 'id' in exinfo and exinfo['id'] != None:
                exercisesInfo = NewExercise.objects.get(pk = exinfo['id'])
                exercisesInfo.exerciseName = exinfo['exerciseName']
                exercisesInfo.exerciseDesc = exinfo['exerciseDesc']
                exercisesInfo.exerciseStatus = exinfo['exerciseStatus']
                exercisesInfo.modifiedBy_id = user
                if 'equipment' in exinfo and exinfo['equipment'] != None:
                    exercisesInfo.equipment = exinfo['equipment']
                if 'preExInstructions' in exinfo and exinfo['preExInstructions'] != None:
                    exercisesInfo.preExInstructions = exinfo['preExInstructions']
                if 'postExInstructions' in exinfo and exinfo['postExInstructions'] != None:
                    exercisesInfo.postExInstructions = exinfo['postExInstructions']
                if 'distanceExists' in exinfo and exinfo['distanceExists'] != None:
                    exercisesInfo.distanceExists = exinfo['distanceExists']
                if 'timeExists' in exinfo and exinfo['timeExists'] != None:
                    exercisesInfo.timeExists = exinfo['timeExists']
                if 'exAbilities' in exinfo and exinfo['exAbilities'] != None:
                    exercisesInfo.exAbilities = exinfo['exAbilities']
                if 'repsExists' in exinfo and exinfo['repsExists'] != None:
                    exercisesInfo.repsExists = exinfo['repsExists']
                if 'weightExists' in exinfo and exinfo['weightExists'] != None:
                    exercisesInfo.weightExists = exinfo['weightExists']
                if 'setInstructions' in exinfo and exinfo['setInstructions'] != None:
                    exercisesInfo.setInstructions = exinfo['setInstructions']
                if 'speedExists' in exinfo and exinfo['speedExists'] != None:
                    exercisesInfo.speedExists=exinfo['speedExists']
                if 'heightExists' in exinfo and exinfo['heightExists'] != None:
                    exercisesInfo.heightExists=exinfo['heightExists']
                if 'setInstContent' in exinfo and exinfo['setInstContent'] != None:
                    exercisesInfo.setInstructions=exinfo['setInstContent']
                if 'timeShortest' in exinfo and exinfo['timeShortest'] != None:
                    exercisesInfo.timeShortest=exinfo['timeShortest']
                if 'flowType' in exinfo and exinfo['flowType']!=None:
                    exercisesInfo.flowType=exinfo['flowType']   
                if 'youtubeUrl' in exinfo and exinfo['youtubeUrl'] !=0 and exinfo['youtubeUrl'] !='0' and exinfo['youtubeUrl'] !=False:
                    if 'video_id__videoLink' in exinfo and exinfo['video_id__videoLink'] != None:
                        if len(exinfo['video_id__videoLink'].split('=')) >1:
                            url = exinfo['video_id__videoLink'].split('=')[1]
                        else:
                            url = exinfo['video_id__videoLink'].split('=')[0]
                        videoLink = Videos.objects.get(id = exercisesInfo.video_id)
                        videoLink.videoLink = url
                        videoLink.save()
                else:
                    if 'videoLink' in exinfo and exinfo['videoLink'] != None:
                        videoLink = Videos.objects.get(id = exercisesInfo.video_id)
                        videoLink.videoLink = exinfo['videoLink']
                        videoLink.save()
                exercisesInfo.save()
                
        
                if 'rmMetValues' in exinfo and exinfo['rmMetValues'] !=None:
                    for metid in exinfo['rmMetValues']:
                        deletemetValues = MetabolicValues.objects.get(pk = metid)
                        deletemetValues.delete()
                if 'metValues' in exinfo and exinfo['metValues'] !=None and exinfo['metValues'] !=[]:
                    for val in exinfo['metValues']['ranges']:
                        if 'id' in val and val['id'] != None:
                            updatemetaVal = MetabolicValues.objects.get(pk = val['id'])
                            updatemetaVal.parameter = exinfo['metValues']['key']
                            updatemetaVal.exercise_id = exercisesInfo.id
                            updatemetaVal.minValue = val['min']
                            updatemetaVal.maxValue = val['max']
                            updatemetaVal.metaValue = val['value']
                            updatemetaVal.save()
                            print('update')
                        else:
                            createMetaValues =MetabolicValues.objects.create(
                                exercise_id =exercisesInfo.id,
                                parameter = exinfo['metValues']['key'],
                                minValue = val['min'],
                                maxValue = val['max'],
                                metaValue = val['value']
                            )
                            createMetaValues.save()
                return JsonResponse({"success": True, "message": "Exercise Updated Successfully", "exId": exercisesInfo.id})
            else:
                if NewExercise.objects.filter(exerciseName=exinfo['exerciseName']).exists():
                    return JsonResponse({"success": False, "message": 'Exercise Name already exists'})
                else:
                    exercises = NewExercise.objects.create(
                        exerciseName = exinfo['exerciseName'],
                        exerciseDesc=exinfo['exerciseDesc'],
                        exerciseStatus = exinfo['exerciseStatus'],
                        createdBy_id=user,
                        modifiedBy_id=user,
                        accessLevel = 1
                    )
                    if 'equipment' in exinfo and exinfo['equipment'] != None:
                        exercises.equipment=exinfo['equipment']
                    if 'preExInstructions' in exinfo and exinfo['preExInstructions'] != None:
                        exercises.preExInstructions=exinfo['preExInstructions']
                    if 'postExInstructions' in exinfo and exinfo['postExInstructions'] != None:
                        exercises.postExInstructions=exinfo['postExInstructions']
                    if 'distanceExists' in exinfo and exinfo['distanceExists'] != None:
                        exercises.distanceExists=exinfo['distanceExists']
                    if 'timeExists' in exinfo and exinfo['timeExists'] != None:
                        exercises.timeExists=exinfo['timeExists']
                    if 'exAbilities' in exinfo and exinfo['exAbilities'] != None:
                        exercises.exAbilities=exinfo['exAbilities']
                    if 'repsExists' in exinfo and exinfo['repsExists'] != None:
                        exercises.repsExists=exinfo['repsExists']
                    if 'weightExists' in exinfo and exinfo['weightExists'] != None:
                        exercises.weightExists=exinfo['weightExists']
                    if 'speedExists' in exinfo and exinfo['speedExists'] != None:
                        exercises.speedExists=exinfo['speedExists']
                    if 'heightExists' in exinfo and exinfo['heightExists'] != None:
                        exercises.heightExists=exinfo['heightExists']
                    if 'setInstContent' in exinfo and exinfo['setInstContent'] != None:
                        exercises.setInstructions=exinfo['setInstContent']
                    if 'timeShortest' in exinfo and exinfo['timeShortest'] != None:
                        exercises.timeShortest=exinfo['timeShortest']
                    if 'flowType' in exinfo and exinfo['flowType']!=None:
                    	exercises.flowType=exinfo['flowType']	
                    exercises.save()
                    
                    
                    if 'video_id__videoLink' in exinfo and exinfo['video_id__videoLink'] != '' and exinfo['video_id__videoLink'] != None:
                        if len(exinfo['video_id__videoLink'].split('=')) >1:
                            url = exinfo['video_id__videoLink'].split('=')[1]
                        else:
                            url = exinfo['video_id__videoLink'].split('=')[0]
                        videoLink = Videos.objects.create(
                            videoLink = url,
                            createdBy_id=user,
                            modifiedBy_id=user
                        )
                        videoLink.save()
                        exVideos = ExcerciseVideos.objects.create(
                            excercise_id = exercises.id,
                            video_id = videoLink.id,
                            createdBy_id=user,
                            modifiedBy_id=user
                        )
                        exVideos.save()
                        exercises.video_id = videoLink.id
                    if 'videoUrl' in exinfo and exinfo['videoUrl'] != '' and exinfo['videoUrl'] != None:
                        videoLink = Videos.objects.create(
                            videoLink = exinfo['videoUrl'],
                            createdBy_id=user,
                            modifiedBy_id=user,
                            youtubeUrl = False
                        )
                        videoLink.save()
                        exVideos = ExcerciseVideos.objects.create(
                            excercise_id = exercises.id,
                            video_id = videoLink.id,
                            createdBy_id=user,
                            modifiedBy_id=user
                        )
                        exVideos.save()
                        exercises.video_id = videoLink.id
                    exercises.save()
                    return JsonResponse({"success":True,"message":"Exercise Saved Successfully","exId":exercises.id})
        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 getExercise(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req ="GET"
    url = "stratadmin/getExercise/"
    try:
        if username != None:
            if 'rows' in request.POST and request.POST['rows'] != '':
                rows = int(request.POST['rows'])
            else:
                rows = 50

            if 'page' in request.POST and request.POST['page'] != '':
                page = int(request.POST['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            userpage = Exercise.objects.values('id','exerciseName','exerciseCode','exerciseStatus',
                                                                   'exerciseDesc','equipment','createdBy','modifiedBy',
                                                                 'createdDate','modifiedDate').order_by('-createdDate')
            userarry = []
            total = len(userpage)
            data = userpage[offset:tot]
            for dt in data:
                print(dt)
                dataObj = dict(dt)
                print(dataObj)
                userarry.append(dataObj )
            return JsonResponse({"success": True, "details": userarry,"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 getExercise1(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req ="GET"
    url = "stratadmin/getExercise/"
    try:
        if username != None:
            if 'rows' in request.POST and request.POST['rows'] != '':
                rows = int(request.POST['rows'])
            else:
                rows = 50

            if 'page' in request.POST and request.POST['page'] != '':
                page = int(request.POST['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            userpage = NewExercise.objects.values('id','exerciseName','exerciseStatus',
                                                                   'exerciseDesc','equipment','createdBy','modifiedBy',
                                                                 'createdDate','modifiedDate').order_by('-createdDate')
            
            userarry = []
            total = len(userpage)
            data = userpage[offset:tot]
            for dt in data:
                print(dt)
                dataObj = dict(dt)
                print(dataObj)
                userarry.append(dataObj )
            return JsonResponse({"success": True, "details": userarry,"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 exerciseSearch(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    exeinfo = json.loads(request.body.decode('utf-8'))#angular-js excdata
    req = exeinfo
    url = "stratadmin/exercisesearch/"
    try:
        if username != None:
            if 'rows' in exeinfo and 'rows' != '':
                rows = int(exeinfo['rows'])
            else:
                rows = 50
            if 'page' in exeinfo and 'page' != '':
                page = int(exeinfo['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            excfilter = Exercise.objects.all().order_by('-modifiedDate')
            if 'excdata' in exeinfo !='':
                if 'exName' in exeinfo['excdata']  and exeinfo['excdata']['exName'] !='':
                    excfilter = excfilter.filter(exerciseName__icontains = exeinfo['excdata']['exName'])
                if 'exCode' in exeinfo['excdata']  and exeinfo['excdata']['exCode'] !='':
                    excfilter = excfilter.filter(exerciseCode__icontains = exeinfo['excdata']['exCode'])
                if 'equipment' in exeinfo['excdata']  and exeinfo['excdata']['equipment'] !='':
                    excfilter = excfilter.filter(equipment__icontains = exeinfo['excdata']['equipment'])
                if 'exerciseStatus' in exeinfo['excdata']  and exeinfo['excdata']['exerciseStatus'] !='':
                    excfilter = excfilter.filter(exerciseStatus = exeinfo['excdata']['exerciseStatus'])
            dataArr = list()
            total = len(excfilter)
            totaldata = excfilter[offset:tot]
            for dt in totaldata:
                dataObj = model_to_dict(dt)
                dataArr.append(dataObj)
                print(dataArr)
            return JsonResponse({"success": True, "details": 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 exerciseSearch1(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    exeinfo = json.loads(request.body.decode('utf-8'))#angular-js excdata
    req = exeinfo
    url = "stratadmin/exercisesearch/"
    try:
        if username != None:
            if 'rows' in exeinfo and 'rows' != '':
                rows = int(exeinfo['rows'])
            else:
                rows = 50
            if 'page' in exeinfo and 'page' != '':
                page = int(exeinfo['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            excfilter = NewExercise.objects.all().order_by('-modifiedDate')
            if 'excdata' in exeinfo !='':
                if 'exName' in exeinfo['excdata']  and exeinfo['excdata']['exName'] !='':
                    excfilter = excfilter.filter(exerciseName__icontains = exeinfo['excdata']['exName'])
                if 'exCode' in exeinfo['excdata']  and exeinfo['excdata']['exCode'] !='':
                    excfilter = excfilter.filter(exerciseCode__icontains = exeinfo['excdata']['exCode'])
                if 'equipment' in exeinfo['excdata']  and exeinfo['excdata']['equipment'] !='':
                    excfilter = excfilter.filter(equipment__icontains = exeinfo['excdata']['equipment'])
                if 'exerciseStatus' in exeinfo['excdata']  and exeinfo['excdata']['exerciseStatus'] !='':
                    excfilter = excfilter.filter(exerciseStatus = exeinfo['excdata']['exerciseStatus'])
            dataArr = list()
            total = len(excfilter)
            totaldata = excfilter[offset:tot]
            for dt in totaldata:
                dataObj = model_to_dict(dt)
                dataArr.append(dataObj)
                print(dataArr)
            return JsonResponse({"success": True, "details": 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 createVideos(request):
    #user = request.session['user_id']
    #print(user)
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    vedioinfo = json.loads(request.body.decode('utf-8'))
    req = vedioinfo
    url = "stratadmin/addVideos/"
    try:
        if username != None:
            print(vedioinfo)
            if 'id' in vedioinfo:
                videoObj, created = Videos.objects.get_or_create(
                    id=vedioinfo['id']
                )
                videoObj.videoLink = vedioinfo['videoLink']
                videoObj.videosStatus = vedioinfo['videosStatus']
                videoObj.modifiedBy_id = user
                videoObj.save()
                return JsonResponse({"success":True,"message":"vedio updated succesfully"})
            else:
                if Videos.objects.filter(videoLink=vedioinfo['videoLink']).exists():
                    return JsonResponse({"success": False, "message": 'video link already exists'})
                videoObj,created = Videos.objects.get_or_create(
                videoLink=vedioinfo['videoLink'],
                videosStatus=vedioinfo['videosStatus'],
                createdBy_id=user,
                modifiedBy_id=user
                )
                return JsonResponse({"success":True,"message":"vedio 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 getVideos(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url = "stratadmin/getVideos/"
    try:
        if username != None:
            if 'rows' in request.POST and request.POST['rows'] != '':
                rows = int(request.POST['rows'])
            else:
                rows = 50

            if 'page' in request.POST and request.POST['page'] != '':
                page = int(request.POST['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            userpage = Videos.objects.values('id', 'videoLink', 'videosStatus', 'createdBy', 'modifiedBy',
                                             'createdDate', 'modifiedDate').order_by('-createdDate')
            total = len(userpage)
            data = userpage[offset:tot]
            userarry = []
            for dt in data:
                dataObj = dict(dt)
                userarry.append(dataObj)
            return JsonResponse({"details": userarry, "total": total})
            #return JsonResponse({"success": True, "details": userarry, "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 videosSearch(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    exeinfo = json.loads(request.body.decode('utf-8'))#angular-js excdata
    req = exeinfo
    url = "stratadmin/videosSearch/"
    try:
        if username != None:
            if 'rows' in exeinfo and 'rows' != '':
                rows = int(exeinfo['rows'])
            else:
                rows = 50
            if 'page' in exeinfo and 'page' != '':
                page = int(exeinfo['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows

            excfilter = Videos.objects.all().order_by('-modifiedDate')
            if 'excdata' in exeinfo !='':
                if 'videoLink' in exeinfo['excdata']  and exeinfo['excdata']['videoLink'] !='':
                    excfilter = excfilter.filter(videoLink__icontains = exeinfo['excdata']['videoLink'])
                if 'videosStatus' in exeinfo['excdata']  and exeinfo['excdata']['videosStatus'] !='':
                    excfilter = excfilter.filter(videosStatus = exeinfo['excdata']['videosStatus'])
            total = len(excfilter)
            totaldata = excfilter[offset:tot]
            dataArr = list()
            for dt in totaldata:
                dataObj = model_to_dict(dt)
                dataArr.append(dataObj)
                print(dataArr)
            return JsonResponse({"details": dataArr, "total": total})
            #return JsonResponse({"success": True, "details": 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 createExcerciseTypeVideos(request):
    #user = request.session['user_id']
    #print(user)
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    vedioinfo = json.loads(request.body.decode('utf-8'))
    req = vedioinfo
    url = "stratadmin/addExcerciseTypeVideos/"
    try:
        if username != None:
            print(vedioinfo)
            if 'id' in vedioinfo:
                details, created = ExcerciseTypeVideos.objects.get_or_create(id=int(vedioinfo['id']))
                print(created)
                print("details", details)
                details.excerciseType_id = vedioinfo['excerciseType']
                details.video_id = int(vedioinfo['video'])
                details.excerciseStatus = vedioinfo['excerciseStatus']
                details.save()
                return JsonResponse({"success": True, "message": "ExcerciseTypeVideo updated successfully"})
            else:
                if ExcerciseTypeVideos.objects.filter(excerciseType=vedioinfo['excerciseType'],video=vedioinfo['video']).exists():
                    return JsonResponse({"success": False, "message": 'excerciseType already exists'})
                vedio = ExcerciseTypeVideos.objects.create(
                    excerciseType_id=vedioinfo['excerciseType'],
                    video_id=vedioinfo['video'],
                    excerciseStatus=vedioinfo['excerciseStatus'],
                    createdBy_id=user,
                    modifiedBy_id=user
                )
                vedio.save()
                return JsonResponse({"success": True, "message": "ExcerciseTypeVideo 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 exerciseTypeVideoSearch(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    exeinfo = json.loads(request.body.decode('utf-8'))  # angular-js excdata
    req =exeinfo
    url = "stratadmin/exerciseTypeVideoSearch/"
    try:
        if username != None:
            if 'rows' in exeinfo and 'rows' != '':
                rows = int(exeinfo['rows'])
            else:
                rows = 50
            if 'page' in exeinfo and 'page' != '':
                page = int(exeinfo['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            #exeinfo = json.loads(request.body.decode('utf-8'))#angular-js excdata
            excfilter = ExcerciseTypeVideos.objects.select_related('ExerciseType__id', 'Videos_id').values('id','excerciseStatus',
                                                                                                  'excerciseType__exerciseTypeName',
                                                                                                  'video__videoLink','modifiedDate',
                                                                                                  'excerciseType', 'video').order_by('-modifiedDate')
            if 'excdata' in exeinfo !='':
                if 'excerciseType' in exeinfo['excdata']  and exeinfo['excdata']['excerciseType'] !='':
                    excfilter = excfilter.filter(excerciseType_id = exeinfo['excdata']['excerciseType'])
                if 'video' in exeinfo['excdata']  and exeinfo['excdata']['video'] !='':
                    excfilter = excfilter.filter(video_id = exeinfo['excdata']['video'])
                if 'excerciseStatus' in exeinfo['excdata']  and exeinfo['excdata']['excerciseStatus'] !='':
                    excfilter = excfilter.filter(excerciseStatus = exeinfo['excdata']['excerciseStatus'])
            total = len(excfilter)
            totaldata = excfilter[offset:tot]
            dataArr = list()
            for dt in totaldata:
                dataObj = dict(dt)
                dataArr.append(dataObj)
                print(dataArr)
            return JsonResponse({"success": True, "details": 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 getExcerciseTypeVideos(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    print(username)
    user = username['id']
    req = "GET"
    url = "stratadmin/getExcerciseTypeVideos/"
    try:
        #user = username['id']
        #print(user)
        if username != None:
            #userpage =ExcerciseTypeVideos.objects.values('id','excerciseType','video','createdBy',
             #                                                      'modifiedBy','createdDate','modifiedDate')
            if 'rows' in request.POST and request.POST['rows'] != '':
                rows = int(request.POST['rows'])
            else:
                rows = 50

            if 'page' in request.POST and request.POST['page'] != '':
                page = int(request.POST['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            userpage = ExcerciseTypeVideos.objects.select_related('ExerciseType__id', 'Videos_id').values('id','excerciseStatus',
                                                                                                  'excerciseType__exerciseTypeName',
                                                                                                  'video__videoLink','createdDate',
                                                                                                  'excerciseType', 'video').order_by('-createdDate')

            total = len(userpage)
            data = userpage[offset:tot]
            userarry = []
            for dt in data:
                #print(dt)
                dataObj = dict(dt)
                print(dataObj)
                userarry.append(dataObj )
            return JsonResponse({"success": True, "details": userarry,"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 createExcerciseVideos(request):
    # user = request.session['user_id']
    # print(user)
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    vedioinfo = json.loads(request.body.decode('utf-8'))
    req = vedioinfo
    url = "stratadmin/addExcerciseVideos/"
    try:
        if username != None:
            print(vedioinfo)
            if 'id' in vedioinfo:
                details = ExcerciseVideos.objects.get(id=vedioinfo['id'])
                details.excercise_id = vedioinfo['excercise']
                details.video_id = vedioinfo['video']
                details.excerciseVideosStatus = vedioinfo['excerciseVideosStatus']
                details.save()
                return JsonResponse({"success": True, "message": "ExcerciseVideo updated successfully"})
            else:
                if ExcerciseVideos.objects.filter(excercise=vedioinfo['excercise'],video=vedioinfo['video']).exists():
                    return JsonResponse({"success": False, "message": 'ExcerciseVideo already exists'})
                vedio = ExcerciseVideos.objects.create(
                    excercise_id=vedioinfo['excercise'],
                    video_id=vedioinfo['video'],
                    excerciseVideosStatus=vedioinfo['excerciseVideosStatus'],
                    createdBy_id=user,
                    modifiedBy_id=user
                )
                vedio.save()
                return JsonResponse({"success": True, "message": "ExcerciseVideo 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 getExcerciseVideos(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url = "stratadmin/getExcerciseVideos/"
    try:
        print(username)
        # user = username['id']
        # print(user)
        if username != None:
            if 'rows' in request.POST and request.POST['rows'] != '':
                rows = int(request.POST['rows'])
            else:
                rows = 50

            if 'page' in request.POST and request.POST['page'] != '':
                page = int(request.POST['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows

            userpage = ExcerciseVideos.objects.select_related('Exercise__id', 'Videos_id').values('id',
                                                                                                  'excerciseVideosStatus',
                                                                                                  'excercise__exerciseName',
                                                                                                  'video__videoLink',
                                                                                                  'excercise','createdDate',
                                                                                                  'video').order_by('-createdDate')
            total = len(userpage)
            data = userpage[offset:tot]
            userarry = []
            for dt in data:
                print(dt)
                dataObj = dict(dt)
                print(dataObj)
                userarry.append(dataObj)
            return JsonResponse({"success": True, "details": userarry,"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 getExcerciseVideos1(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url = "stratadmin/getExcerciseVideosv2/"
    try:
        print(username)
        
        # user = username['id']
        # print(user)
        if username != None:
            if 'rows' in request.POST and request.POST['rows'] != '':
                rows = int(request.POST['rows'])
            else:
                rows = 50

            if 'page' in request.POST and request.POST['page'] != '':
                page = int(request.POST['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows

            userpage = ExcerciseVideos.objects.select_related('NewExercise__id', 'Videos_id').values('id',
                                                                                                  'excerciseVideosStatus',
                                                                                                  'excercise__exerciseName',
                                                                                                  'video__videoLink',
                                                                                                  'excercise','createdDate',
                                                                                                  'video').order_by('-createdDate')
            total = len(userpage)
            data = userpage[offset:tot]
            userarry = []
            for dt in data:
                print(dt)
                dataObj = dict(dt)
                print(dataObj)
                userarry.append(dataObj)
            return JsonResponse({"success": True, "details": userarry,"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 exerciseVideoSearch(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    exeinfo = json.loads(request.body.decode('utf-8'))#angular-js excdata
    req = exeinfo
    url = "stratadmin/exerciseVideoSearch/"
    try:
        if username != None:
            if 'rows' in exeinfo and 'rows' != '':
                rows = int(exeinfo['rows'])
            else:
                rows = 50
            if 'page' in exeinfo and 'page' != '':
                page = int(exeinfo['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            excfilter = ExcerciseVideos.objects.select_related('Exercise__id', 'Videos_id').values('id',
                                                                                                  'excerciseVideosStatus',
                                                                                                  'excercise__exerciseName',
                                                                                                  'video__videoLink',
                                                                                                  'excercise','modifiedDate',
                                                                                                  'video').order_by('-modifiedDate')
            if 'excdata' in exeinfo!='':
                if 'excercise' in exeinfo['excdata']  and exeinfo['excdata']['excercise'] !='':
                    excfilter = excfilter.filter(excercise_id = exeinfo['excdata']['excercise'])
                if 'video' in exeinfo['excdata']  and exeinfo['excdata']['video'] !='':
                    excfilter = excfilter.filter(video_id = exeinfo['excdata']['video'])
                if 'excerciseVideosStatus' in exeinfo['excdata']  and exeinfo['excdata']['excerciseVideosStatus'] !='':
                    excfilter = excfilter.filter(excerciseVideosStatus = exeinfo['excdata']['excerciseVideosStatus'])

            total = len(excfilter)
            totaldata = excfilter[offset:tot]
            dataArr = list()
            for dt in totaldata:
                dataObj = dict(dt)
                dataArr.append(dataObj)
                print(dataArr)
            return JsonResponse({"success": True, "details": 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 exerciseVideoSearch1(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    exeinfo = json.loads(request.body.decode('utf-8'))#angular-js excdata
    req = exeinfo
    url = "stratadmin/exerciseVideoSearchv2/"
    try:
        if username != None:
            if 'rows' in exeinfo and 'rows' != '':
                rows = int(exeinfo['rows'])
            else:
                rows = 50
            if 'page' in exeinfo and 'page' != '':
                page = int(exeinfo['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            excfilter = ExcerciseVideos.objects.select_related('NewExercise__id', 'Videos_id').values('id',
                                                                                                  'excerciseVideosStatus',
                                                                                                  'excercise__exerciseName',
                                                                                                  'video__videoLink',
                                                                                                  'excercise','modifiedDate',
                                                                                                  'video').order_by('-modifiedDate')
            if 'excdata' in exeinfo!='':
                if 'excercise' in exeinfo['excdata']  and exeinfo['excdata']['excercise'] !='':
                    excfilter = excfilter.filter(excercise_id = exeinfo['excdata']['excercise'])
                if 'video' in exeinfo['excdata']  and exeinfo['excdata']['video'] !='':
                    excfilter = excfilter.filter(video_id = exeinfo['excdata']['video'])
                if 'excerciseVideosStatus' in exeinfo['excdata']  and exeinfo['excdata']['excerciseVideosStatus'] !='':
                    excfilter = excfilter.filter(excerciseVideosStatus = exeinfo['excdata']['excerciseVideosStatus'])

            total = len(excfilter)
            totaldata = excfilter[offset:tot]
            dataArr = list()
            for dt in totaldata:
                dataObj = dict(dt)
                dataArr.append(dataObj)
                print(dataArr)
            return JsonResponse({"success": True, "details": 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 createProgramType(request):
    #user = request.session['user_id']
    #print(user)
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    ptinfo = json.loads(request.body.decode('utf-8'))
    req = ptinfo
    url = "stratadmin/addProgramType/"
    try:
        if username != None:
            print(ptinfo)
            if 'id' in ptinfo:
                pObj, created = ProgramType.objects.get_or_create(
                    id=ptinfo['id']
                )
                pObj.programTypeName = ptinfo['programTypeName']
                pObj.programTypeStatus = ptinfo['programTypeStatus']
                pObj.modifiedBy_id = user
                pObj.save()
                return JsonResponse({"success":True,"message":"programTypeNames updated succesfully"})
            else:
                if ProgramType.objects.filter(programTypeName=ptinfo['programTypeName']).exists():
                    return JsonResponse({"success": False, "message": 'programTypeName already exists'})
                pObj, created = ProgramType.objects.get_or_create(
                    programTypeName=ptinfo['programTypeName'],
                    programTypeStatus=ptinfo['programTypeStatus'],
                    createdBy_id=user,
                    modifiedBy_id=user
                )
                return JsonResponse({"success":True,"message":"programTypeName 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 programTypeSearch(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    exeinfo = json.loads(request.body.decode('utf-8'))#angular-js excdata
    req = exeinfo
    url = "stratadmin/programTypeSearch/"
    try:
        if username != None:
            if 'rows' in exeinfo and 'rows' != '':
                rows = int(exeinfo['rows'])
            else:
                rows = 50
            if 'page' in exeinfo and 'page' != '':
                page = int(exeinfo['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            excfilter = ProgramType.objects.all().order_by('-modifiedDate')
            if 'excdata' in exeinfo !='':
                if 'programTypeName' in exeinfo['excdata']  and exeinfo['excdata']['programTypeName'] !='':
                    excfilter = excfilter.filter(programTypeName__icontains = exeinfo['excdata']['programTypeName'])
                if 'programTypeStatus' in exeinfo['excdata']  and exeinfo['excdata']['programTypeStatus'] !='':
                    excfilter = excfilter.filter(programTypeStatus = exeinfo['excdata']['programTypeStatus'])
            dataArr = list()
            total = len(excfilter)
            totaldata = excfilter[offset:tot]
            for dt in totaldata:
                dataObj = model_to_dict(dt)
                dataArr.append(dataObj)
                print(dataArr)
            return JsonResponse({"success": True, "details": 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 getProgramType(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url = "stratadmin/getProgramType/"
    try:
        print(username)
        #user = username['id']
        #print(user)
        if username != None:
            if 'rows' in request.POST and request.POST['rows'] != '':
                rows = int(request.POST['rows'])
            else:
                rows = 50

            if 'page' in request.POST and request.POST['page'] != '':
                page = int(request.POST['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows

            userpage =ProgramType.objects.values('id','programTypeName','programTypeStatus','createdBy','modifiedBy',
                                                                   'createdDate','modifiedDate').order_by('-createdDate')
            userarry = []
            total = len(userpage)
            data = userpage[offset:tot]
            for dt in data:
                print(dt)
                dataObj = dict(dt)
                print(dataObj)
                userarry.append(dataObj )
            return JsonResponse({"success": True, "details": userarry,"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 createGoals(request):
    #user = request.session['user_id']
    #print(user)
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    goalinfo = json.loads(request.body.decode('utf-8'))
    req = goalinfo
    url = "stratadmin/addGoals/"
    try:
        if username != None:
            #goalDetails = Goals.objects.filter(goalName= goalinfo['goalName'])
            if 'id' in goalinfo:
                details =Goals.objects.get(id=goalinfo['id'])
                details.goalName=goalinfo['goalName']
                details.goalStatus =goalinfo['goalStatus']
                details.save()
                return JsonResponse({"success":True,"message":"Goal Updated Successfully"})
            else:
                if Goals.objects.filter(goalName=goalinfo['goalName']).exists():
                    return JsonResponse({"success": False, "message": 'GoalName already exists'})
                goal = Goals.objects.create(
                    goalName=goalinfo['goalName'],
                    goalStatus=goalinfo['goalStatus'],
                    #parentGoal_id=goalinfo['parentGoal_id'],
                    createdBy_id = user,
                    modifiedBy_id=user
                )
                goal.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 getGoals(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url = "stratadmin/getGoals/"
    try:
        print(username)
        #user = username['id']
        #print(user)
        if username != None:
            if 'rows' in request.POST and request.POST['rows'] != '':
                rows = int(request.POST['rows'])
            else:
                rows = 50

            if 'page' in request.POST and request.POST['page'] != '':
                page = int(request.POST['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            userpage =Goals.objects.values('id','goalName','goalStatus',
                                                                   'createdBy','modifiedBy','createdDate','modifiedDate').order_by('-createdDate')
            userarry = []
            total = len(userpage)
            data = userpage[offset:tot]
            for dt in data:
                #print(dt)
                dataObj = dict(dt)
                #print(dataObj)
                userarry.append(dataObj )
            return JsonResponse({"success": True, "details": userarry,"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 goalSearch(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    exeinfo = json.loads(request.body.decode('utf-8'))#angular-js excdata
    req = exeinfo
    url = "stratadmin/goalSearch/"
    try:
        if username != None:
            print(exeinfo)
            if 'rows' in exeinfo and 'rows' != '':
                rows = int(exeinfo['rows'])
            else:
                rows = 50
            if 'page' in exeinfo and 'page' != '':
                page = int(exeinfo['page'])
            else:
                page = 1

            offset = (page - 1) * rows
            tot = page * rows

            excfilter = Goals.objects.all().order_by('-modifiedDate')
            if 'excdata' in exeinfo !='':
                if 'goalName' in exeinfo['excdata']  and exeinfo['excdata']['goalName'] !='':
                    excfilter = excfilter.filter(goalName__icontains = exeinfo['excdata']['goalName'])
                if 'goalStatus' in exeinfo['excdata']  and exeinfo['excdata']['goalStatus'] !='':
                    excfilter = excfilter.filter(goalStatus__icontains = exeinfo['excdata']['goalStatus'])
            dataArr = list()
            total = len(excfilter)
            totaldata = excfilter[offset:tot]
            for dt in totaldata:
                dataObj = model_to_dict(dt)
                dataArr.append(dataObj)
                #print(dataArr)
            return JsonResponse({"success": True, "details": 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 createInolRange(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    inolRangeinfo = json.loads(request.body.decode('utf-8'))
    req = inolRangeinfo
    url = "stratadmin/addInolRange/"
    try:
        if username != None:
            print(inolRangeinfo)
            if 'id' in inolRangeinfo:
                details = InolRange.objects.get(id=inolRangeinfo['id'])
                details.level=inolRangeinfo['level']
                details.minValue = inolRangeinfo['minValue']
                details.maxValue =inolRangeinfo['maxValue']
                details.avgValue = inolRangeinfo['avgValue']
                details.stressValue = inolRangeinfo['stressValue']
                details.inolRangeStatus = inolRangeinfo['inolRangeStatus']
                details.save()
                return JsonResponse({"success": True, "message": "InolRange Upade successfully"})
                #return JsonResponse({"success":False,"message":"InolRange Already exists"})
            else:
                if InolRange.objects.filter(level=inolRangeinfo['level']).exists():
                    return JsonResponse({"success": False, "message": 'InolRange already exists'})
                inolRanges = InolRange.objects.create(
                level=inolRangeinfo['level'],
                minValue=inolRangeinfo['minValue'],
                maxValue=inolRangeinfo['maxValue'],
                avgValue=inolRangeinfo['avgValue'],
                stressValue=inolRangeinfo['stressValue'],
                inolRangeStatus = inolRangeinfo['inolRangeStatus'],
                createdBy_id = user,
                modifiedBy_id=user
                )
                inolRanges.save()
                return JsonResponse({"success":True,"message":"InolRange 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 getInolRange(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url = "stratadmin/getInolRange/"
    try:
        print(username)
        #user = username['id']
        #print(user)
        if username != None:
            if 'rows' in request.POST and request.POST['rows'] != '':
                rows = int(request.POST['rows'])
            else:
                rows = 50

            if 'page' in request.POST and request.POST['page'] != '':
                page = int(request.POST['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            userpage =InolRange.objects.values('id','level','minValue','maxValue',
                                                                   'avgValue','stressValue','inolRangeStatus',
                                               'createdBy','modifiedBy','createdDate','modifiedDate').order_by('-createdDate')
            userarry = []
            total = len(userpage)
            data = userpage[offset:tot]
           # print(data)
            for dt in data:
               # print(dt)
                dataObj = dict(dt)
               # print(dataObj)
                userarry.append(dataObj )
            return JsonResponse({"success": True, "details": userarry,"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 inolRangeSearch(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    exeinfo = json.loads(request.body.decode('utf-8'))#angular-js excdata
    req = exeinfo
    url = "stratadmin/inolRangeSearch/"
    try:
        if username != None:
            if 'rows' in exeinfo and 'rows' != '':
                rows = int(exeinfo['rows'])
            else:
                rows = 50
            if 'page' in exeinfo and 'page' != '':
                page = int(exeinfo['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            excfilter = InolRange.objects.all().order_by('-modifiedDate')
            if 'excdata' in exeinfo !='':
                if 'level' in exeinfo['excdata']  and exeinfo['excdata']['level'] !='':
                    excfilter = excfilter.filter(level__icontains = exeinfo['excdata']['level'])
                if 'minValue' in exeinfo['excdata']  and exeinfo['excdata']['minValue'] !='':
                    excfilter = excfilter.filter(minValue__icontains = exeinfo['excdata']['minValue'])
                if 'maxValue' in exeinfo['excdata']  and exeinfo['excdata']['maxValue'] !='':
                    excfilter = excfilter.filter(maxValue__icontains = exeinfo['excdata']['maxValue'])
                if 'avgValue' in exeinfo['excdata']  and exeinfo['excdata']['avgValue'] !='':
                    excfilter = excfilter.filter(avgValue__icontains = exeinfo['excdata']['avgValue'])
                if 'stressValue' in exeinfo['excdata']  and exeinfo['excdata']['stressValue'] !='':
                    excfilter = excfilter.filter(stressValue__icontains = exeinfo['excdata']['stressValue'])
                if 'inolRangeStatus' in exeinfo['excdata']  and exeinfo['excdata']['inolRangeStatus'] !='':
                    excfilter = excfilter.filter(inolRangeStatus = exeinfo['excdata']['inolRangeStatus'])
            dataArr = list()
            total = len(excfilter)
            totaldata = excfilter[offset:tot]
            for dt in totaldata:
                dataObj = model_to_dict(dt)
                dataArr.append(dataObj)
               # print(dataArr)
            return JsonResponse({"success": True, "details": 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 createCountry(request):
    #user = request.session['user_id']
    #print(user)
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    countryinfo = json.loads(request.body.decode('utf-8'))
    req = countryinfo
    url = "stratadmin/addCountry/"
    try:
        if username != None:
            print(countryinfo)
            if 'id' in countryinfo:
                details =Country.objects.get(id=countryinfo['id'])
                details.name=countryinfo['name']
                details.countryStatus =countryinfo['countryStatus']
                details.save()
                return JsonResponse({"success":True,"message":"Country name Updated Successfully"})
            else:
                if Country.objects.filter(name=countryinfo['name']).exists():
                    return JsonResponse({"success": False, "message": 'Country name already exists'})
                country = Country.objects.create(
                name=countryinfo['name'],
                countryStatus=countryinfo['countryStatus'],
                createdBy_id = user,
                modifiedBy_id=user
                )
                country.save()
                return JsonResponse({"success":True,"message":"Country name 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 getCountry(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url = "stratadmin/getCountry/"
    try:
        print(username)
        #user = username['id']
        #print(user)
        if username != None:
            if 'rows' in request.POST and request.POST['rows'] != '':
                rows = int(request.POST['rows'])
            else:
                rows = 50

            if 'page' in request.POST and request.POST['page'] != '':
                page = int(request.POST['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            userpage =Country.objects.values('id','name','countryStatus',
                                                                   'createdBy','modifiedBy','createdDate','modifiedDate').order_by('-createdDate')
            userarry = []
            total = len(userpage)
            data = userpage[offset:tot]
            for dt in data:
                #print(dt)
                dataObj = dict(dt)
                #print(dataObj)
                userarry.append(dataObj )
            return JsonResponse({"success": True, "details": userarry,"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 countrySearch(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    exeinfo = json.loads(request.body.decode('utf-8'))
    req = exeinfo
    url = "stratadmin/countrySearch/"
    try:
        if username != None:
            if 'appreq' in exeinfo and exeinfo['appreq']==1:
                #print('appreq-----true')
                cntrydata = Country.objects.values('id', 'name', 'countryCode', 'dialCode').filter(countryStatus=1).order_by('id')
                if 'countryname' in exeinfo and exeinfo['countryname'] !='':
                    cntrydata = cntrydata.filter(name__istartswith=exeinfo['countryname'])
                cntryArr = []
                for dt in cntrydata:
                    cntryObj = dict(dt)
                    cntryArr.append(cntryObj)
                return HttpResponse(json.dumps(cntryArr))
            else:
                #print('appreq-----false')
                if 'rows' in exeinfo and 'rows' != '':
                    rows = int(exeinfo['rows'])
                else:
                    rows = 50
                if 'page' in exeinfo and 'page' != '':
                    page = int(exeinfo['page'])
                else:
                    page = 1

                offset = (page - 1) * rows
                tot = page * rows

                excfilter = Country.objects.values('id','name','countryCode','dialCode').filter(countryStatus = 1).order_by('id')
                if 'excdata' in exeinfo !='':
                    if 'name' in exeinfo['excdata']  and exeinfo['excdata']['name'] !='':
                        excfilter = excfilter.filter(name__istartswith = exeinfo['excdata']['name'])
                    if 'countryStatus' in exeinfo['excdata']  and exeinfo['excdata']['countryStatus'] !='':
                        excfilter = excfilter.filter(countryStatus__icontains = exeinfo['excdata']['countryStatus'])
                dataArr = list()
                total = len(excfilter)
                totaldata = excfilter[offset:tot]
                for dt in totaldata:
                    dataObj = dict(dt)
                    dataArr.append(dataObj)
                    #print(dataArr)
                return JsonResponse({"success": True, "details": 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 createState(request):
    #user = request.session['user_id']
    #print(user)
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    stateinfo = json.loads(request.body.decode('utf-8'))
    req = stateinfo
    url = "stratadmin/addState/"
    try:
        if username != None:
            print(stateinfo)
            if 'id' in stateinfo:
                details =State.objects.get(id=stateinfo['id'])
                details.country_id= stateinfo['country']
                details.name=stateinfo['name']
                details.stateStatus =stateinfo['stateStatus']
                details.save()
                return JsonResponse({"success":True,"message":"State name Updated Successfully"})
            else:
                if State.objects.filter(country=stateinfo['country'],name=stateinfo['name']).exists():
                    return JsonResponse({"success": False, "message": 'State name already exists'})
                state = State.objects.create(
                country_id=stateinfo['country'],
                name=stateinfo['name'],
                stateStatus=stateinfo['stateStatus'],
                createdBy_id = user,
                modifiedBy_id=user
                )
                state.save()
                return JsonResponse({"success":True,"message":"State name 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 getStates(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url = "stratadmin/getStates/"
    try:
        print(username)
        #user = username['id']
        #print(user)
        if username != None:
            #userpage =ExcerciseTypeVideos.objects.values('id','excerciseType','video','createdBy',
             #                                                      'modifiedBy','createdDate','modifiedDate')
            if 'rows' in request.POST and request.POST['rows'] != '':
                rows = int(request.POST['rows'])
            else:
                rows = 50

            if 'page' in request.POST and request.POST['page'] != '':
                page = int(request.POST['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            userpage = State.objects.select_related('Country__id').values('id','country','name','stateStatus',
                                                                              'country__name',
                                                                                'createdDate').order_by('-createdDate')

            total = len(userpage)
            data = userpage[offset:tot]
            userarry = []
            for dt in data:
                #print(dt)
                dataObj = dict(dt)
                print(dataObj)
                userarry.append(dataObj )
            return JsonResponse({"success": True, "details": userarry,"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 stateSearch(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    exeinfo = json.loads(request.body.decode('utf-8'))#angular-js excdata
    req = exeinfo
    url = "stratadmin/stateSearch/"
    try:
        if username != None:
            print(exeinfo)
            if 'rows' in exeinfo and 'rows' != '':
                rows = int(exeinfo['rows'])
            else:
                rows = 50
            if 'page' in exeinfo and 'page' != '':
                page = int(exeinfo['page'])
            else:
                page = 1

            offset = (page - 1) * rows
            tot = page * rows

            excfilter =State.objects.select_related('Country__id').values('id','country','name','stateStatus','country__name',
                                                                                'createdDate').order_by('-modifiedDate')
            if 'excdata' in exeinfo !='':
                if 'country' in exeinfo['excdata']  and exeinfo['excdata']['country'] !='':
                    excfilter = excfilter.filter(country_id = exeinfo['excdata']['country'])
                if 'state' in exeinfo['excdata']  and exeinfo['excdata']['state'] !='':
                    excfilter = excfilter.filter(name__icontains = exeinfo['excdata']['state'])
                if 'stateStatus' in exeinfo['excdata']  and exeinfo['excdata']['stateStatus'] !='':
                    excfilter = excfilter.filter(stateStatus__icontains = exeinfo['excdata']['stateStatus'])
            dataArr = list()
            total = len(excfilter)
            totaldata = excfilter[offset:tot]
            for dt in totaldata:
                dataObj = dict(dt)
                dataArr.append(dataObj)
                #print(dataArr)
            return JsonResponse({"success": True, "details": 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)})

import pyexcel as pe

'''@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def some_view(request):
    print("here")
    stratsessionutil = StartFitSessionUtil()
    try:
        username = stratsessionutil.get_user_insession(request)
        if username != None:
            print("in here")
            filename = request.FILES['myfile'].name
            extension = filename.split(".")[1]
            content = request.FILES['myfile'].read()
            sheet = pe.get_sheet(file_type=extension, file_content=content, name_columns_by_row=0)
            # then use it as usual
            records = sheet.to_records()
            for list in records:
                print(list['name'])
                country = Country.objects.create(
                name=list['name']
                #countryStatus=list['countryStatus']
                #createdBy_id=user,
                #modifiedBy_id=user)
                )
                country.save()
            return JsonResponse({"success": True, "message": "Country name Saved Successfully"})

    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg": str(e)})
'''
def countryuploadfile(request):
    # Create the HttpResponse object with the appropriate CSV header.
    filename = request.FILES['file'].name
    extension = filename.split(".")[1]
    content = request.FILES['file'].read()
    sheet = pe.get_sheet(file_type=extension, file_content=content, name_columns_by_row=0)
    # then use it as usual
    records = sheet.to_records()
    print(records)
    for list in records:
        if Country.objects.filter(name=list['name']).exists():
            return JsonResponse({"success": False, "message": 'Country name already exists'})
        print(list['name'])
        country = Country.objects.create(
            name=list['name'],
            countryStatus=True,
            createdBy_id=1,
            modifiedBy_id=1
        )
        country.save()
    return JsonResponse({"success": True, "message": "Country name Saved Successfully"})


@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def createExerciseCategory(request):
    #user = request.session['user_id']
    #print(user)
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
        #print(username)
    user = username['id']
    info = json.loads(request.body.decode('utf-8'))
    req = info
    url = "stratadmin/addExerciseCategory/"
    try:
        #print(user,"id")
        if username != None:
            print(info)
            if 'id' in info:
                details = ExerciseCategory.objects.get(id=info['id'])
                print(details)
                details.categoryName = info['categoryName']
                details.status=info['status']
                details.save()
                return JsonResponse({"success":True,"message":"Category Updated Successfully"})
            else:
                if ExerciseCategory.objects.filter(categoryName=info['categoryName']).exists():
                    return JsonResponse({"success": False, "message": 'Category already exists'})

                exTypes = ExerciseCategory.objects.create(
                    categoryName = info['categoryName'],
                    status=info['status'],
                    createdBy_id=user,
                    modifiedBy_id=user
                )
                exTypes.save()
                return JsonResponse({"success":True,"message":"Category 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 getExerciseCategory(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    print(username)
    user = username['id']
    req = "GET"
    url = "stratadmin/getExerciseCategory/"
    try:
        #user = username['id']
        #print(user)
        if username != None:
            if 'rows' in request.POST and request.POST['rows'] != '':
                rows = int(request.POST['rows'])
            else:
                rows = 50

            if 'page' in request.POST and request.POST['page'] != '':
                page = int(request.POST['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            userpage = ExerciseCategory.objects.values('id','categoryName','status','createdBy','modifiedBy',
                                                                 'createdDate','modifiedDate').order_by('-createdDate')
            userarry = []
            total = len(userpage)
            data = userpage[offset:tot]
            for dt in data:
                #print(dt)
                dataObj = dict(dt)
                print(dataObj)
                userarry.append(dataObj )
            return JsonResponse({"success": True, "details": userarry,"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 exerciseCategorySearch(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    exeinfo = json.loads(request.body.decode('utf-8'))
    req = exeinfo
    url = "stratadmin/exerciseCategorySearch/"
    try:
        if username != None:
            print(exeinfo)
            if 'rows' in exeinfo and 'rows' != '':
                rows = int(exeinfo['rows'])
            else:
                rows = 50
            if 'page' in exeinfo and 'page' != '':
                page = int(exeinfo['page'])
            else:
                page = 1
            offset = (page - 1) * rows
            tot = page * rows
            excfilter = ExerciseCategory.objects.all().order_by('-modifiedDate')
            if 'excdata' in exeinfo !='':
                if 'categoryName' in exeinfo['excdata']  and exeinfo['excdata']['categoryName'] !='':
                    excfilter = excfilter.filter(categoryName__icontains = exeinfo['excdata']['categoryName'])
                if 'status' in exeinfo['excdata']  and exeinfo['excdata']['status'] !='':
                    excfilter = excfilter.filter(status = exeinfo['excdata']['status'])
            dataArr = list()
            total = len(excfilter)
            totaldata = excfilter[offset:tot]
            for dt in totaldata:
                dataObj = model_to_dict(dt)
                dataArr.append(dataObj)
                print(dataArr)
            return JsonResponse({"success": True, "details": 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 getParentGoals(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    req = "GET"
    url = "stratadmin/getParentGoals/"
    try:
        if username != None:
            print('getParentGoals')
            dataArr =[]
            getGoals = Goals.objects.values('id','goalName','goalStatus')
            for dt in getGoals:
                data = dict(dt)
                if data['goalStatus'] == 1:
                    dataArr.append(data)
            return JsonResponse({"success":True,"details":dataArr})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(user, req, url, str(e))
        return JsonResponse({"msg": str(e)})
