import collections
import random
from dateutil.relativedelta import relativedelta
from django.shortcuts import render

# Create your views here.
from django.core.mail import EmailMultiAlternatives
from django.db import connection
from django.http import JsonResponse, HttpResponse
from django.template import Context
from django.template.loader import render_to_string, get_template
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
# Create your views here.
import json
from datetime import datetime, timedelta, time,timezone
from django.db.models import Max
from rest_framework.decorators import api_view, authentication_classes
from datetime import date
from Plan.models import PlanSession, PlanExcercise, PlanSets, SelectedAbilities, PlanGoals, PlanRating
from Plan.views import celeblikes, celebreviewList
from Subscriber.Authentication import StartFitAuthentication,SessionAuthentication,StartFitSessionUtil, AuthResponse,IsAuthenticated
from Subscriber.models import User, Userfollow, FitnessProfile
from Userplan.models import UserPlan, UserSets, UserExercise
from Celebrity.models import CelebrityComments,CelebrityLikes, CelebrityUploads, CelebrityPlansLikes, CelebrityDetails
from Subscriber.views import exceptionMail, dictfetchall
from StratFit import settings
from utility.models import PriceMapping, PriceConversion, Videos
from utility.models import Exercise

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def getCelebrityList(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    url="celebrity/getCelebrityList/"
    x = connection.cursor()
    try:
        celebrities="SELECT su.id, su.first_name, su.last_name, su.userPrivacy, su.username, su.avatar, su.userCover,fp.gender,cc.about,cc.designation,cc.favworkout, COUNT(sf.followingUser_id) AS followingCount, uc.country as userCountry , (SELECT sff.status FROM `Subscriber_userfollow` sff WHERE `followingUser_id` = "+str(user)+"  AND `followerUser_id` = su.id) AS followStatus FROM `Subscriber_user` su LEFT JOIN `Celebrity_celebritydetails` cc ON su.id = cc.userid_id LEFT JOIN `Subscriber_fitnessprofile` fp ON fp.user_id = su.id LEFT JOIN `Subscriber_userfollow` sf ON su.id = sf.`followerUser_id` LEFT JOIN `Subscriber_useraddress` uc ON uc.user_id = su.id WHERE su.userType = 8 AND su.userPrivacy = 0 GROUP BY sf.`followerUser_id` "
        x.execute(celebrities)
        resultQuery = dictfetchall(x)
        arr=[]
        if resultQuery:
            for celebrity in resultQuery:
                val=dict(celebrity)
                val['celebrityFullName'] = val['first_name'] + " " + val['last_name']
                if val['avatar'] is None:
                    if val['gender'] ==1:
                        val['avatar'] = 'http://stratfit.net/assets/images/user1.png'
                    elif val['gender'] == 2:
                        val['avatar'] = 'http://stratfit.net/assets/images/user2.png'
                    else:
                        val['avatar'] = 'http://stratfit.net/assets/images/user1.png'
                elif val['avatar'] is not None:
                    val['avatar'] = settings.S3URL + val['avatar']
                if val['userCover'] is not None:
                    val['userCover'] = settings.S3URL + val['userCover']
                if val['followStatus'] is None or val['followStatus'] =='':
                    val['followStatus'] = 0
		
                val['liveStatus'] = 0
                userActivePlan = UserPlan.objects.values('id','user_id','plan_id','status').filter(status =1,user_id=val['id'])
                if userActivePlan.exists():
                    for dt4 in userActivePlan:
                        activeObj = dict(dt4)
                        if activeObj['user_id'] == val['id']:
                            today = datetime.now(timezone.utc)
                            userlive = UserSets.objects.filter(plan_id=activeObj['plan_id'],user_id = val['id']).filter(createdDate__year=today.year, createdDate__month=today.month, createdDate__day=today.day).values().last()
                            if userlive:
                                if userlive['user_id'] == val['id']:
                                    diff_time = today - userlive['createdDate']
                                    totalSeconds = diff_time.total_seconds()
                                    if totalSeconds == 0 or totalSeconds <=1800:
                                        val['liveStatus'] = 1
                                    else:
                                        val['liveStatus'] = 0
                                else:
                                    val['liveStatus'] = 0
                            else:
                                val['liveStatus'] = 0
                if(username['userType'] == 8 and val['id']== user) or (val['userPrivacy'] == 0) and (username['userCountry'] == val['userCountry']):
                    arr.append(val)
        return JsonResponse({"success": True,"celebrities":arr})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def completeSetDetails(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    data = json.loads(request.body.decode('utf-8'))
    req = data
    url="celebrity/completedSetDetails/"
    try:
        if username != None:
            userplanDetails = UserPlan.objects.filter(user_id = data['id'],status = 1).values('id','plan_id')
            for val in userplanDetails:
                plan_id = val['plan_id']
                userplan_id = val['id']
            offset1 = data['end']
            print(offset1)
            offset2 = data['start']
            print(offset2)
            info=UserSets.objects.filter(plan_id=plan_id).select_related('id','UserExercise__id','Exercise','PlanSets').values('setNumber','userexercise__exerciseId__exerciseName','totalReps','userexercise__exerciseWorkWeight','planset__num_of_reps')
            list=[]
            for dt in info:
                plandetails=dict(dt)
                plandetails['numOfReps'] = plandetails['planset__num_of_reps']
                plandetails['setName'] = plandetails['setNumber']
                plandetails['repsDone'] = plandetails['totalReps']
                plandetails['exerciseName'] = plandetails['userexercise__exerciseId__exerciseName']
                plandetails['workWeight'] = plandetails['userexercise__exerciseWorkWeight']
                list.append(plandetails)
            last_two = PlanSession.objects.values('id').order_by('-id')[int(offset2):int(offset1)]
            last_two_in_ascending_order = reversed(last_two)
            arr=[]
            for dt1 in last_two_in_ascending_order:
                details=dict(dt1)
                userSetDetails = UserSets.objects.select_related('id','UserExercise__id', 'Exercise','PlanSets').filter(planset__excercise__session__id = details['id']).values('setNumber', 'userexercise__exerciseId__exerciseName','totalReps','userexercise__exerciseWorkWeight', 'planset__num_of_reps')
                for val in userSetDetails:
                    values = dict(val)
                    print(values,"--------")
                    arr.append(values)
            return JsonResponse({"plan": list,"offset":arr,"userplanId":userplan_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 saveComment(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    comment = json.loads(request.body.decode('utf-8'))
    req = comment
    url="celebrity/saveComment/"
    try:
        if username != None:
            userComment = CelebrityComments.objects.create(
                planId_id=comment['plan_id'],
                comment = comment['comment'],
                createdBy_id = user
            )
            userComment.save()
            return JsonResponse({"success":True, "message":"comment 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)})

@never_cache
def getComments(request):
    try:
        plan = json.loads(request.body.decode('utf-8'))
        userComment = CelebrityComments.objects.select_related('User').filter(planId_id=plan['userPlanId']).values('createdBy_id__first_name','planId_id','comment','id','createdDate','createdBy_id')
        commentObj = []
        for dt in userComment:
            dta = dict(dt)
            dta['createdDate'] = dta['createdDate'].strftime("%Y-%m-%d")
            commentObj.append(dta)
        return JsonResponse({"success":True, "data":commentObj})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def saveCelebrityLiveComment(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    comment = json.loads(request.body.decode('utf-8'))
    req = comment
    url="celebrity/saveComment/"
    try:
        if username != None:
            planDetails = UserPlan.objects.filter(user_id=comment['celebrityID'], status=1).values('id')
            for dt in planDetails:
                values = dict(dt)
            userComment = CelebrityComments.objects.create(
                celebrityId_id=comment['celebrityID'],
                comment = comment['comment'],
                planId_id=values['id'],
                createdBy_id = user
            )
            userComment.save()
            return JsonResponse({"success":True, "message":"comment saved successfully"})
        else:
            return JsonResponse({"success":False,"message":"User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(req, url, str(e))
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def getCelebrityLiveComments(request):
    data = json.loads(request.body.decode('utf-8'))
    req=data
    url="celebrity/getComments"
    try:
        celebrityDetails = CelebrityComments.objects.filter(celebrityId=data['celebrityID'], planId__status=1).values(
            'id', 'planId__plan__planName', 'comment', 'createdBy_id', 'createdBy_id__first_name','createdDate',
            'createdBy_id__avatar')
        commentObj = []
        for dt in celebrityDetails:
            dta = dict(dt)
            dta['createdDate'] = dta['createdDate'].strftime("%Y-%m-%d")
            commentObj.append(dta)
        count = celebrityDetails.count()
        return JsonResponse({"success":True, "data":commentObj,"commentCount":count})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail('',req, url, str(e))
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def celebrityDetails(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user=username['id']
    print("username",username)
    data = json.loads(request.body.decode('utf-8'))
    req = data
    url = "celebrity/celebrityDetails/"
    try:
        if username != None:
            if username['userType'] == 8:
                usertypeDetails=User.objects.filter(userType=data['userType']).values('id','first_name','last_name','avatar').exclude(id = user)
            else:
                usertypeDetails = User.objects.filter(userType=data['userType']).values('id', 'first_name','last_name','avatar')
            list=[]
            for val in usertypeDetails:
                details=dict(val)
                print("details",details)
                details["celbrityName"] = details['first_name'] + ' ' + details['last_name']
                details["celebrityId"] = details['id']
                details["following"] = 0
                details['liveStatus'] = 0
                usertypeDetails1 = Userfollow.objects.select_related('User__id').filter(followingUser=details["id"]).count()
                if usertypeDetails1 > 0:
                    details["following"] = 1
                else:
                    details['following'] = 0
                details['followingCount'] = usertypeDetails1
                list.append(details)
            return JsonResponse({"success": True, "celebrity_list":list })
        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 celebrity(request):
    stratsessionutil = StartFitSessionUtil()
    try:
        username = stratsessionutil.get_user_insession(request)
        print(username)
        celebrities=User.objects.filter(userType=8).values('id','first_name','last_name','username')
        #print(celebrities,"celebriteis")
        arr=[]
        for celebrity in celebrities :
            print(celebrity)
            val=dict(celebrity)
            print(val)
            arr.append(val)
        return JsonResponse({"success": True,"celebrities":arr})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def likeHit(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    setData = json.loads(request.body.decode('utf-8'))
    req=setData
    url = "celebrity/likeHit/"
    try:
        if username != None:
            userComment = CelebrityLikes.objects.create(
                createdBy_id = user,
                celebrityId_id = setData['celeb_id'],
                set_id = setData['set_id']
            )
            userComment.save()
            return JsonResponse({"success":True, "message":"Like saved successfully"})
        else:
            return JsonResponse({"success":False,"message":"User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def celebrityPlanInfo(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    print("user name",username)
    user = username['id']
    name=username['first_name']
    data = json.loads(request.body.decode('utf-8'))
    try:
        if username != None:
            followCount = Userfollow.objects.filter(followingUser_id=data['celebrityId']).select_related('User__id').count()
            count = followCount
            planDetails = UserPlan.objects.filter(user__id=data['celebrityId'], status=1).values('plan__planName','plan__id','plan__price','plan__planGoal__goalName','plan__programType','plan__createdBy__first_name','user__first_name','user__avatar')
            print("planDetails",planDetails)
            list=[]
            if len(planDetails) > 0:
                for dt in planDetails:
                    plan=dict(dt)
                    plan['PlanID']=plan['plan__id']
                    plan['PlanPrice']=plan['plan__price']
                    plan['PlanGoal']=plan['plan__planGoal__goalName']
                    plan['PlanLevel']=plan['plan__programType']
                    plan['PlanName']=plan['plan__planName']
                    plan['PlanCreatedBy'] = plan['plan__createdBy__first_name']
                    celebrityName = plan['user__first_name']
                    celebrityImage = plan['user__avatar']
                    list.append(plan)
            else:
                userInfo = User.objects.filter(id=data['celebrityId']).values()
                for dt in userInfo:
                    userDet = dict(dt)
                    celebrityName = userDet['first_name']
            return JsonResponse({"success": True, "followCount": count,"CelebrityName":celebrityName, "CelebrityImage":celebrityImage, "PlanInfo":list})
        else:
            return JsonResponse({"success": False, "message": "User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        #exceptionMail(user, req, url, str(e))

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def uploadImage(request):
    stratsessionutil = StartFitSessionUtil()
    try:
        username = stratsessionutil.get_user_insession(request)
        user = username['id']
        upload = json.loads(request.body.decode('utf-8'))
        if username != None:
            if 'mediaId' in upload and upload['mediaId'] !='':
                updateUpload = CelebrityUploads.objects.get(pk=upload['mediaId'])
                updateUpload.status = 0
                updateUpload.save()
                return JsonResponse({"success": True, "message": "Deleted Successfuly"})
            else:
                setId = UserSets.objects.filter(userplan_id =upload['userplanId'],planexercise_id =upload['exId'],planset_id = upload['setId'] ).values()
                if setId.exists():
                    for val in setId:
                        valObj = dict(val)
                        celbupload = CelebrityUploads.objects.create(
                            userexercise_id = valObj['userexercise_id'],
                            userSet_id = valObj['id'],
                            #imageUrl = upload['image'],
                            user_id = user
                        )
                        if 'image' in upload and upload['image'] != '':
                            celbupload.imageUrl = upload['image']
                            message = "Image uploaded successfully"
                        if 'video' in upload and upload['video'] != '':
                            celbupload.videoUrl = upload['video']
                            message = "Video uploaded successfully"
                        celbupload.save()
                    return JsonResponse({"success":True, "message":message})
                else:
                    return JsonResponse({"success": False, "message": "No set details found"})
        else:
            return JsonResponse({"success":False,"message":"User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def getWorkFeed(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    dataReq = json.loads(request.body.decode('utf-8'))
    try:
        if username != None:
            print("I am here celebrity workfeed")
            userPlanObj = UserPlan.objects.filter(user_id=dataReq['user_id'], status=1).values()
            for dt in userPlanObj:
                uPlan = dict(dt)
                print(uPlan)
                userPlanID = uPlan['id']
            allSetDataObj = UserSets.objects.select_related('User__id','PlanSets__id','PlanExcercise__id','PlanSession__id','Microcycle__id','PlanMesocycle','PlanPeriods','Plan__id').filter(userplan_id = userPlanID).values('user_id__first_name','session_id','setNumber','totalReps','setWorkWeight','setExercise','userexercise','exercise_id','planset__excercise__session__microcycle__mesocycle__period__plan__planName','createdDate','exercise')
            totalSessionDet = collections.defaultdict(list)
            sessionArr = {}
            username = ''
            planName = ''
            sesionDate = ''
            for dt in allSetDataObj:
                setObj = dict(dt)
                plexDet  = PlanExcercise.objects.filter(session_id = setObj['session_id'],exerciseName_id = setObj['exercise']).values()
                if plexDet.exists():
                    for pex in plexDet:
                        pexObj = dict(pex)
                        setObj['prescReps'] = pexObj['num_of_reps']
                        setObj['prescSets'] = pexObj['num_of_sets']
                planName = setObj['planset__excercise__session__microcycle__mesocycle__period__plan__planName']
                username = setObj['user_id__first_name']
                setObj['createdDate'] = setObj['createdDate'].strftime("%Y/%m/%d")
                totalSessionDet[str(setObj['session_id'])].append(setObj)
            print(totalSessionDet)
            return JsonResponse({"success": True, "data": totalSessionDet,"username":username,"planName":planName})
        else:
            return JsonResponse({"success": False, "message": "User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        #exceptionMail(user, req, url, str(e))

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def uploadVideo(request):
    stratsessionutil = StartFitSessionUtil()
    try:
        username = stratsessionutil.get_user_insession(request)
        user = username['id']
        upload = json.loads(request.body.decode('utf-8'))
        if username != None:
            if 'video' in  upload:
                celbupload = CelebrityUploads.objects.create(
                    userexercise_id = upload['ex_id'],
                    videoUrl = upload['video'],
                    user_id = user
                )
                celbupload.save()
                return JsonResponse({"success":True, "message":"video uploaded successfully"})
        else:
            return JsonResponse({"success":False,"message":"User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def commentList(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    try:
        if username != None:
            if username['userType'] == 8:
                celebrityDetails=CelebrityComments.objects.select_related('User','UserPlan','Plan').filter(planId__status=1).values('id','planId__plan__planName','comment','createdBy_id','createdBy_id__first_name')
                list=[]
                for dt in celebrityDetails:
                    details=dict(dt)
                    list.append(details)
                count=celebrityDetails.count()
                return JsonResponse({"success": True,"commentList":list,"commentCount":count})
            else:
                return JsonResponse({"success": False, "message":'You are not a celebrity'})
        else:
            return JsonResponse({"success": False, "message": "User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def postLike(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    setData = json.loads(request.body.decode('utf-8'))
    req=setData
    url = "celebrity/likeHit/"
    try:
        if username != None:
            usertype = User.objects.get(id=setData['celebrityID'])
            if usertype.userType == 8:
                if UserSets.objects.filter(user_id=setData['celebrityID']).exists:
                    setDetails = UserSets.objects.filter(user_id=setData['celebrityID']).values('id')
                    for dt in setDetails:
                        values = dict(dt)
                    if CelebrityLikes.objects.filter(createdBy_id=user, set_id=values['id']).exists():
                        return JsonResponse({"success": False, "message": 'you have already liked this post'})
                    userComment = CelebrityLikes.objects.create(
                        celebrityId_id=setData['celebrityID'],
                        set_id=values['id'],
                        createdBy_id=user
                    )
                    userComment.save()
                    return JsonResponse({"success":True, "message":"Like saved successfully"})
                else:
                    return JsonResponse({"success": False, "message": "The user does not started any exercise."})
            else:
                return JsonResponse({"success": False, "message": "It is not a celebrity ID"})
        else:
            return JsonResponse({"success":False,"message":"User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        #exceptionMail(req, url, str(e))
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def likeList(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    req="GET"
    url="celebrity/likeList"
    data = json.loads(request.body.decode('utf-8'))
    try:
        if username != None:
            list=[]
            likeDetails = CelebrityLikes.objects.filter(celebrityId=data['celebrityID']).select_related('User', 'UserSets').values('id','createdBy_id', 'createdBy_id__first_name')
            print(likeDetails)
            for dt in likeDetails:
                values=dict(dt)
                list.append(values)
            count=likeDetails.count()
            return JsonResponse({"success":True,"message":list,"LikeCount":count})
        else:
            return JsonResponse({"success": False, "message": "User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail(req, url, str(e))
        return JsonResponse({"msg":str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def sendText(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user_id = username['id']
    data = json.loads(request.body.decode('utf-8'))
    req=data
    url="celebrity/sendText"
    try:
        if username != None:
            planId=UserExercise.objects.filter(planexercise_id=data['ex_id'],user_id=user_id).values('id')
            if planId.exists():
                for dt in planId:
                    val=dict(dt)
                    value=val['id']
                    celbDetails=CelebrityUploads.objects.filter(userexercise_id=value,user_id=user_id).values('id')
                    if celbDetails.exists():
                        for dt in celbDetails:
                            values=dict(dt)
                            ids=values['id']
                        details=CelebrityUploads.objects.get(id=ids)
                        details.text=data['text']
                        details.save()
                        return JsonResponse({"success": True, "message": "Text updated successfully"})
                    else:
                        text = CelebrityUploads.objects.create(
                            userexercise_id = value,
                            text = data['text'],
                            user_id = user_id
                        )
                        text.save()
                        return JsonResponse({"success":True,"message":"Text saved successfully"})
            else:
                return JsonResponse({"success": False, "message": "ExerciseId does not exists"})
        else:
            return JsonResponse({"success":False,"message":"User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        exceptionMail('',req, url,str(e))
        return JsonResponse({"msg": str(e)})

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def getWorkFeed1(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    dataReq = json.loads(request.body.decode('utf-8'))
    try:
        if username != None:
            planexCount = 0
            #print("I am here celebrity workfeed")
            weightUnit = FitnessProfile.objects.filter(user_id = user).values().last()
            allSetDataObj = UserSets.objects.select_related('User__id','PlanSets__id','PlanExcercise__id','PlanSession__id','Microcycle__id','PlanMesocycle','PlanPeriods','Plan__id','Exercise','Videos').filter(user_id=dataReq['user_id'],userplan_id = dataReq['user_plan_id'],setDate__contains = datetime.date(datetime.strptime(dataReq['createdDate'], '%Y-%m-%d'))).values('id','user_id__first_name','session_id','setNumber','totalReps','setWorkWeight','setExercise','userexercise','exercise_id','planset__excercise__session__microcycle__mesocycle__period__plan__planName','createdDate','exercise','exercise_id__exerciseDesc','exercise_id__video_id__videoLink','planexercise_id','planset_id','user_id','sessionStatus','advTime','advDistance','exercise_id__exerciseName','exercise_id__workFormula')
            #print(allSetDataObj,"alll")
            totalSessionDet = []
            #sessionArr = []
            tempExName=''
            mainArr = []
            msgArr = [{"setdone":["Lifted %w%%wm% for all reps %r%X%r%","Check this out - Lifted %w%%wm% for all reps %r%X%r%","Folks - Done lifting %w%%wm% for all reps %r%X%r%"],"setnotdone":["Finished lifting %w%%wm% %r% out of %tr% reps. Missed Reps today","That was tough. Finished lifting %w%%wm% %r% out of %tr% reps","Bro. Rough Day. Finished lifting %w%%wm% %r% out of %tr% reps"]}]
            setnotDoneArr = []
            username = ''
            planName = ''
            tempExId=''
            tempExid1 = ''
            sessionStatus = 0
            session_id = 0
            celebrity = False
            for dt in allSetDataObj:
                setObj = dict(dt)
                setObj['images'] = []
                setObj['videos'] = []
                setObj['comments'] = []
                sessionStatus = setObj['sessionStatus']
                session_id = setObj['session_id']
                setObj['ex_id'] = setObj['planexercise_id']
                if tempExid1 == '' or tempExid1 != setObj['exercise_id']:
                    tempExid1 = setObj['exercise_id']
                    sessionArr = []
                exName = Exercise.objects.get(id=setObj['exercise_id'])
                setObj['exerciseName'] = exName.exerciseName
                advEx = exName.accessLevel
                exDesc = setObj['exercise_id__exerciseDesc']
                exVideo = setObj['exercise_id__video_id__videoLink']
                exWarmUp = False
                planName = setObj['planset__excercise__session__microcycle__mesocycle__period__plan__planName']
                username = setObj['user_id__first_name']
                celebCOmments = CelebrityComments.objects.filter(userset_id = setObj['id'],status = 1).values()
                print(setObj['id'],"1232323223")
                if celebCOmments.exists():
                    for cm in celebCOmments:
                        cmObj = dict(cm)
                        setObj['comments'].append(cmObj)
                celebUploads = CelebrityUploads.objects.select_related('UserSets__id').filter(userSet_id=setObj['id'],status = 1).values()
                if celebUploads.exists():
                    for img in celebUploads:
                        imgObj = dict(img)
                        if imgObj['imageUrl'] != '' and imgObj['imageUrl'] != None:
                            setObj['images'].append({"id":imgObj['id'],"url":imgObj['imageUrl']})
                        if imgObj['videoUrl'] != '' and imgObj['videoUrl'] != None:
                            setObj['videos'].append({"id":imgObj['id'],"url":imgObj['videoUrl']})
                plexDet = PlanExcercise.objects.filter(session_id=setObj['session_id'],exerciseName_id=setObj['exercise']).values()
                if plexDet.exists():
                    for pex in plexDet:
                        pexObj = dict(pex)
                        setObj['prescReps'] = pexObj['num_of_reps']
                        setObj['prescSets'] = pexObj['num_of_sets']
                        setObj['exWeight'] = pexObj['exWeight']
                        setObj['exTime'] = pexObj['exTime']
                        setObj['exDistance'] = pexObj['exDistance']
                        setObj['intensity'] = pexObj['intensity']
                        if pexObj['warmup'] == 1:
                            exWarmUp = True
                msgIndex = random.randint(0,2)
                if advEx == 0:
                    if setObj['prescReps'] == setObj['totalReps']:
                        tempMsg = msgArr[0]['setdone'][msgIndex].replace('%w%', str(setObj['setWorkWeight'])).replace('%wm%', weightUnit['weightUnit']).replace('%r%', str(setObj['totalReps']))
                    else:
                        tempMsg = msgArr[0]['setnotdone'][msgIndex].replace('%w%', str(setObj['setWorkWeight'])).replace('%wm%', weightUnit['weightUnit']).replace('%r%', str(setObj['totalReps'])).replace('%tr%', str(setObj['prescReps']))
                else:
                    tempMsg = "Completed "+setObj['exercise_id__exerciseName'] +" with:"
                    if setObj['totalReps'] != '' and  setObj['totalReps'] != None and setObj['totalReps']!=0:
                        tempMsg += " <br> Reps: "+str(setObj['totalReps'])+"/"+str(setObj['prescReps'])
                    if setObj['setWorkWeight'] != '' and  setObj['setWorkWeight'] != None and setObj['setWorkWeight']!=0:
                        tempMsg += " <br> Work weight: " + str(setObj['setWorkWeight']) + "/" + str(setObj['exWeight']) +" "+str(weightUnit['weightUnit'])
                    if setObj['advTime'] != '' and  setObj['advTime'] != None and setObj['advTime']!=0:
                        tempMsg += " <br> Time: " + str(setObj['advTime']) + "/" + str(setObj['exTime'])+" minutes"
                    if setObj['advDistance'] != '' and  setObj['advDistance'] != None and setObj['advDistance']!=0:
                        tempMsg += " <br> Time: " + str(setObj['advDistance']) + "/" + str(setObj['exDistance'])+" meters"
                setObj['workoutMsg'] = tempMsg
                tempExName = setObj['exerciseName']
                sessionArr.append(setObj)
                sessionId = setObj['session_id']
                if  tempExId == '' or tempExId != setObj['exercise_id']:
                    tempExId = setObj['exercise_id']
                    if tempExId != '':
                        if setObj['user_id'] == user:
                            celebrity = True
                        totalSessionDet.append({"exerciseName": tempExName, "exId":setObj['exercise'],"exFormula":setObj['exercise_id__workFormula'],"exDesc": exDesc, "exVideo": exVideo, "warmup": exWarmUp,"sets": sessionArr, "workoutMsg": setObj['workoutMsg'],"advExercise":advEx,"intensity":setObj['intensity'],"workWeight":setObj['setWorkWeight']})
                planexCount = PlanExcercise.objects.filter(session_id=sessionId).values().count()
                #totalSessionDet.append({"sets": setObj})
                # sessionArr.append({"exerciseName":setObj['exerciseName'],"sets":totalSessionDet})
            #mainArr.append(totalSessionDet)
            #sessionArr["exerciseName"].append(totalSessionDet)
            #print(totalSessionDet)
            return JsonResponse({"success": True, "data": totalSessionDet,"username":username,"planName":planName,"planExCount":planexCount,"sessionStatus":sessionStatus,"session_id":session_id,"celebrity":celebrity})
        else:
            return JsonResponse({"success": False, "message": "User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        #exceptionMail(user, req, url, str(e))

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def celebritiesPlans(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    data = json.loads(request.body.decode('utf-8'))
    try:
        userCurrency = User.objects.get(id = user)
        celeb = User.objects.get(id = data['celebId'])
        currencyValues = PriceConversion.objects.get(id=1)
        inrValue = currencyValues.inrValue
        likedplans = getLikedPlans(user ,data['celebId'],data['deviceType'],userCurrency,username,inrValue)
        #reviewedplans = getplanReviews(data['celebId'],data['deviceType'],userCurrency,username,inrValue)
        if celeb.userType == 8:
            uplan = UserPlan.objects.select_related('User__id','Plan__id','ProgramType__id').values('id','user_id','user_id__first_name','user_id__last_name','user_id__email','plan_id','plan_id__planName','status','plan_id__planPhoto','plan_id__planLogo','status','plan_id__createdBy_id','plan_id__createdBy_id__first_name','plan_id__createdBy_id__last_name','plan_id__createdBy_id__avatar','plan_id__price','plan_id__indianIosPrice','plan_id__iosPrice','plan_id__indianPrice','plan_id__originalPlanner_id','plan_id__planDescription','plan_id__licencePolicy','plan_id__programType__programTypeName').filter(user_id = data['celebId']).order_by('status').order_by('-id')
            print(len(uplan),"here")
            planArr = []
            prevPlanArr=[]
            futurePlanArr = []
            activePlanArr = []
            totalusercount = 0
            for dt in uplan:
                planObj = dict(dt)
                planObj['userPlanId'] = planObj['id']
                clelebLikes = celeblikes(planObj['plan_id'])
                celebReviews = celebreviewList(planObj['plan_id'])
                planObj['planlikes'] = clelebLikes
                planObj['planreviews'] = celebReviews

                planObj['celeblikedPlan'] = 0
                planObj['celebreviewPlan'] = 0
                planObj['reviews'] = ''

                plalikescount = CelebrityPlansLikes.objects.filter(plan_id = planObj['plan_id'],status = 1).count()
                reviewscount = CelebrityPlansLikes.objects.filter(plan_id =planObj['plan_id']).exclude(reviews__isnull=True).exclude(reviews__exact='').count()
                planObj['planlikesCount'] = plalikescount
                planObj['reviewsCount'] = reviewscount

                celebplanlikes = CelebrityPlansLikes.objects.filter(plan_id = planObj['plan_id'],user_id = user,status =1).values()
                if celebplanlikes.exists():
                    planObj['celeblikedPlan'] = 1
                celebplanreviews = CelebrityPlansLikes.objects.filter(plan_id = planObj['plan_id'],user_id = user).values()
                if celebplanreviews.exists():
                    for celbdt in celebplanreviews:
                        celbObj = dict(celbdt)
                        if celbObj['reviews'] != '' and celbObj['reviews'] != None:
                            planObj['reviews'] = celbObj['reviews']
                            planObj['celebreviewPlan'] = 1

                planObj['coachName'] = planObj['plan_id__createdBy_id__first_name'] + " " + planObj['plan_id__createdBy_id__last_name']
                if 'deviceType' in data and data['deviceType'] == 'ios':
                    if userCurrency.currencyType == "INR":
                        if username['userCountry'] == 88:
                            planObj['price'] = planObj['plan_id__indianIosPrice']
                            planObj['planPrice'] = planObj['price']
                        else:
                            planObj['price'] = planObj['plan_id__iosPrice']
                            planObj['planPrice'] = planObj['price']
                        if int(planObj['plan_id__price']) == 0:
                            planObj['price'] = "Free"
                            planObj['planPrice'] = planObj['price']
                    else:
                        if username['userCountry'] == 88:
                            usdValue = PriceMapping.objects.values().filter(inr=planObj['plan_id__indianIosPrice'])
                        else:
                            usdValue = PriceMapping.objects.values().filter(inr=planObj['plan_id__iosPrice'])
                        for usd in usdValue:
                            usdObj = dict(usd)
                            dollarVal = usdObj['usd']
                        planObj['price'] = dollarVal
                        if int(planObj['plan_id__price']) == 0:
                            planObj['price'] = "Free"
                            planObj['planPrice'] = planObj['price']
                else:
                    if int(planObj['plan_id__price']) == 0:
                        planObj['price'] = "Free"
                        planObj['planPrice'] = planObj['price']
                    else:
                        if userCurrency.currencyType == "INR":
                            if username['userCountry'] == 88:
                                planObj['price'] = round((planObj['plan_id__indianPrice']) * float(inrValue))
                                planObj['planPrice'] = planObj['price']
                            else:
                                planObj['price'] = round((planObj['plan_id__price']) * float(inrValue))
                                planObj['planPrice'] = planObj['price']
                        else:
                            if username['userCountry'] == 88:
                                planObj['price'] = planObj['plan_id__indianPrice']
                                planObj['planPrice'] = planObj['price']
                            else:
                                planObj['price'] = planObj['plan_id__price']
                                planObj['planPrice'] = planObj['price']
                        if float(planObj['plan_id__price']) == 0:
                            planObj['price'] = "Free"
                            planObj['planPrice'] = planObj['price']
                        if planObj['price'] ==0:
                            planObj['price'] ="Free"
                            planObj['planPrice'] = planObj['price']
                planAbilityVal = SelectedAbilities.objects.select_related('PlanAbilities').filter(plan_id=planObj['plan_id']).values('ability_id__ability')
                abilitieslists = ''
                for val in planAbilityVal:
                    valObj = dict(val)
                    abilitieslists += ", " + valObj['ability_id__ability']
                if abilitieslists != '':
                    planAbilities = abilitieslists[1:]
                else:
                    planAbilities = ""
                planPurposesVal = PlanGoals.objects.select_related('PlanPurposes').filter(plan_id=planObj['plan_id']).values('planGoal_id__GoalName')
                purposes = ''
                for val in planPurposesVal:
                    valObj = dict(val)
                    purposes += ", " + valObj['planGoal_id__GoalName']
                if purposes != '':
                    planGoals = purposes[1:]
                else:
                    planGoals = ""
                if planObj['plan_id__originalPlanner_id'] != planObj['plan_id__createdBy_id']:
                    coachVal = User.objects.get(id=planObj['plan_id__originalPlanner_id'])
                    coachName = coachVal.first_name
                    planObj['oriCoachName'] = coachName
                planObj['planDescription'] = planObj['plan_id__planDescription'] + "<br><br><font><b>Purposes:</b> " + str(
                    planGoals) + "</font>"
                if planObj['plan_id__licencePolicy'] == "3" or planObj['plan_id__licencePolicy'] == "White-Label":
                    partnerName = User.objects.get(id=planObj['plan_id__createdBy_id'])
                    planObj['planDescription'] = str(planObj['plan_id__planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
                else:
                    if planObj['plan_id__originalPlanner_id'] != planObj['plan_id__createdBy_id']:
                        coachVal = User.objects.get(id=planObj['plan_id__originalPlanner_id'])
                        coachName = coachVal.first_name + " " + coachVal.last_name
                        planObj['oriCoachName'] = coachName
                    coachName = User.objects.get(id=planObj['plan_id__originalPlanner_id'])
                    planObj['planDescription'] = str(
                        planObj['plan_id__planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(
                        str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
                downloadUsers = UserPlan.objects.filter(plan_id=planObj['plan_id']).count()
                ratingObj = PlanRating.objects.filter(plan=planObj['plan_id']).values()
                totalRate = 0
                userCount = 1
                for rt in ratingObj:
                    rateObj = dict(rt)
                    totalRate = totalRate + rateObj['rating']
                    userCount = userCount + 1
                rating = totalRate / userCount
                planObj['planPurpose'] = planAbilities
                planObj['plan_goals'] = planGoals
                planObj['planType'] = planObj['plan_id__programType__programTypeName']
                planObj['planCompetency'] = "0"
                planObj['planUsers'] = downloadUsers
                totalusercount = totalusercount + int(downloadUsers)
                planObj['PlanRating'] = rating
                planObj['coachId'] = planObj['plan_id__createdBy_id']
                planObj['createdBy'] = planObj['plan_id__createdBy_id']
                planObj['createdBy_id__avatar'] = planObj['plan_id__createdBy_id__avatar']
                planObj['indianIosPrice'] = planObj['plan_id__indianIosPrice']
                planObj['indianPrice'] = planObj['plan_id__indianPrice']
                planObj['iosPrice'] = planObj['plan_id__iosPrice']
                planObj['licencePolicy'] = planObj['plan_id__licencePolicy']
                planObj['originalPlanner_id'] = planObj['plan_id__originalPlanner_id']
                planObj['planName'] = planObj['plan_id__planName']
                planObj['id'] = planObj['plan_id']
                if planObj['planType'] == "STARTER":
                    planObj['ptype'] = 'S'
                elif planObj['planType'] == "INTERMEDIATE":
                    planObj['ptype'] = 'I'
                elif planObj['planType'] == "ADVANCED":
                    planObj['ptype'] = 'A'

                if planObj['plan_id__planPhoto'] is not None:
                    planObj['planPhoto'] = settings.S3URL + planObj['plan_id__planPhoto']
                else:
                    planObj['planPhoto'] = planObj['plan_id__planPhoto']
                if planObj['plan_id__planLogo'] is not None:
                    planObj['planLogo'] = settings.S3URL + planObj['plan_id__planLogo']
                else:
                    planObj['planLogo'] = planObj['plan_id__planLogo']
                planObj['coachId'] = planObj['plan_id__createdBy_id']
                planObj['previousPlan'] = 0
                planObj['activePlan'] = 0
                planObj['futurePlan'] = 0
                if planObj['status'] == 2:
                    planObj['previousPlan'] = 1
                if planObj['status'] == 1:
                    planObj['activePlan'] = 1
                if planObj['status'] == 3:
                    planObj['futurePlan'] = 1
                doneSessions = UserSets.objects.filter(userplan_id = planObj['id']).values('session_id', 'createdDate', 'setDate')
                if doneSessions.exists():
                    planObj['likeStatus'] = 0
                    planObj['reviewStatus'] = 0
                    temp = 0
                    if likedplans !=[]:
                        for planId in likedplans:
                            print(planId,'------01---')
                            temp = temp +1
                            if planObj['status'] != 1:
                                if planObj['plan_id'] == planId['plan_id']:
                                    if planId['likeStatus'] == 1 and planId['reviewStatus'] == 1:
                                        planObj['likeStatus'] = 1
                                        planObj['reviewStatus']  = 1
                                        indices = temp -1
                                        del likedplans[indices]

                                    elif planId['likeStatus'] == 0 and planId['reviewStatus'] == 1:
                                        #planObj['likeStatus'] = 1
                                        planObj['reviewStatus'] = 1
                                        indices = temp - 1
                                        del likedplans[indices]

                                    elif planId['likeStatus'] == 1 and planId['reviewStatus'] == 0:
                                        planObj['likeStatus'] = 1
                                        #planObj['reviewStatus'] = 1
                                        indices = temp - 1
                                        del likedplans[indices]

                                    elif planId['likeStatus'] == 0 and planId['reviewStatus'] == 0:
                                        planObj['likeStatus'] = 0
                                        planObj['reviewStatus'] = 0
                                        indices = temp - 1
                                        del likedplans[indices]
                planArr.append(planObj)
            return JsonResponse({"success": True,"activePlanArr":planArr,"likedPlans":likedplans, "luctype": userCurrency.currencyType})
    except Exception as e:
        logger.exception("something wrong")

def getLikedPlans(luser,userid,deviceType,userCurrency,username,inrValue):
    totalusercount = 0
    celeblikesplans = CelebrityPlansLikes.objects.select_related('User__id', 'Plan__id', 'ProgramType__id').values('user_id','user_id__first_name','user_id__last_name','user_id__email','plan_id','plan_id__planName','status','plan_id__planPhoto','plan_id__planLogo','status','plan_id__createdBy_id','plan_id__createdBy_id__first_name','plan_id__createdBy_id__last_name','plan_id__createdBy_id__avatar','plan_id__price','plan_id__indianIosPrice','plan_id__iosPrice','plan_id__indianPrice','plan_id__originalPlanner_id','plan_id__planDescription','plan_id__licencePolicy','plan_id__programType__programTypeName','reviews').filter(user_id = userid)
    dataArr = []
    if celeblikesplans.exists():
        for dt in celeblikesplans:
            planObj = dict(dt)
            if planObj['status'] == 1:
                planObj['likeStatus'] = 1
            else:
                planObj['likeStatus'] = 0
            if planObj['reviews'] !='' and  planObj['reviews'] !=None:
                planObj['reviewStatus'] = 1
            else:
                planObj['reviewStatus'] = 0
            planObj['coachName'] = planObj['plan_id__createdBy_id__first_name'] + " " + planObj['plan_id__createdBy_id__last_name']

            clelebLikes = celeblikes(planObj['plan_id'])
            celebReviews = celebreviewList(planObj['plan_id'])
            planObj['planlikes'] = clelebLikes
            planObj['planreviews'] = celebReviews

            planObj['celeblikedPlan'] = 0
            planObj['celebreviewPlan'] = 0
            planObj['reviews'] = ''

            plalikescount = CelebrityPlansLikes.objects.filter(plan_id = planObj['plan_id'],status = 1).count()
            reviewscount = CelebrityPlansLikes.objects.filter(plan_id =planObj['plan_id']).exclude(reviews__isnull=True).exclude(reviews__exact='').count()
            planObj['planlikesCount'] = plalikescount
            planObj['reviewsCount'] = reviewscount
			
            celebplanlikes = CelebrityPlansLikes.objects.filter(plan_id = planObj['plan_id'],user_id = luser,status =1).values()
            if celebplanlikes.exists():
                planObj['celeblikedPlan'] = 1
            celebplanreviews = CelebrityPlansLikes.objects.filter(plan_id = planObj['plan_id'],user_id = luser).values()
            if celebplanreviews.exists():
                for celbdt in celebplanreviews:
                    celbObj = dict(celbdt)
                    if celbObj['reviews'] != '' and celbObj['reviews'] != None:
                        planObj['reviews'] = celbObj['reviews']
                        planObj['celebreviewPlan'] = 1

            if deviceType == 'ios':
                if userCurrency.currencyType == "INR":
                    if username['userCountry'] == 88:
                        planObj['price'] = planObj['plan_id__indianIosPrice']
                        planObj['planPrice'] = planObj['price']
                    else:
                        planObj['price'] = planObj['plan_id__iosPrice']
                        planObj['planPrice'] = planObj['price']
                    if int(planObj['plan_id__price']) == 0:
                        planObj['price'] = "Free"
                else:
                    if username['userCountry'] == 88:
                        usdValue = PriceMapping.objects.values().filter(inr=planObj['plan_id__indianIosPrice'])
                    else:
                        usdValue = PriceMapping.objects.values().filter(inr=planObj['plan_id__iosPrice'])
                    for usd in usdValue:
                        usdObj = dict(usd)
                        dollarVal = usdObj['usd']
                    planObj['price'] = dollarVal
                    if int(planObj['plan_id__price']) == 0:
                        planObj['price'] = "Free"
                        planObj['planPrice'] = planObj['price']
            else:
                if int(planObj['plan_id__price']) == 0:
                    planObj['price'] = "Free"
                    planObj['planPrice'] = planObj['price']
                else:
                    if userCurrency.currencyType == "INR":
                        if username['userCountry'] == 88:
                            planObj['price'] = round((planObj['plan_id__indianPrice']) * float(inrValue))
                            planObj['planPrice'] = planObj['price']
                        else:
                            planObj['price'] = round((planObj['plan_id__price']) * float(inrValue))
                            planObj['planPrice'] = planObj['price']
                    else:
                        if username['userCountry'] == 88:
                            planObj['price'] = planObj['plan_id__indianPrice']
                            planObj['planPrice'] = planObj['price']
                        else:
                            planObj['price'] = planObj['plan_id__price']
                            planObj['planPrice'] = planObj['price']
                    if float(planObj['plan_id__price']) == 0:
                        planObj['price'] = "Free"
                        planObj['planPrice'] = planObj['price']
                    if planObj['price'] == 0:
                        planObj['price'] = "Free"
                        planObj['planPrice'] = planObj['price']
            planAbilityVal = SelectedAbilities.objects.select_related('PlanAbilities').filter(plan_id=planObj['plan_id']).values('ability_id__ability')
            abilitieslists = ''
            for val in planAbilityVal:
                valObj = dict(val)
                abilitieslists += ", " + valObj['ability_id__ability']
            if abilitieslists != '':
                planAbilities = abilitieslists[1:]
            else:
                planAbilities = ""
            planPurposesVal = PlanGoals.objects.select_related('PlanPurposes').filter(plan_id=planObj['plan_id']).values(
                'planGoal_id__GoalName')
            purposes = ''
            for val in planPurposesVal:
                valObj = dict(val)
                purposes += ", " + valObj['planGoal_id__GoalName']
            if purposes != '':
                planGoals = purposes[1:]
            else:
                planGoals = ""
            if planObj['plan_id__originalPlanner_id'] != planObj['plan_id__createdBy_id']:
                coachVal = User.objects.get(id=planObj['plan_id__originalPlanner_id'])
                coachName = coachVal.first_name
                planObj['oriCoachName'] = coachName
            planObj['planDescription'] = planObj['plan_id__planDescription'] + "<br><br><font><b>Purposes:</b> " + str(
                planGoals) + "</font>"
            if planObj['plan_id__licencePolicy'] == "3" or planObj['plan_id__licencePolicy'] == "White-Label":
                partnerName = User.objects.get(id=planObj['plan_id__createdBy_id'])
                planObj['planDescription'] = str(
                    planObj['plan_id__planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(
                    str(partnerName.first_name) + " " + str(partnerName.last_name)) + ". All rights reserved.</h6>"
            else:
                if planObj['plan_id__originalPlanner_id'] != planObj['plan_id__createdBy_id']:
                    coachVal = User.objects.get(id=planObj['plan_id__originalPlanner_id'])
                    coachName = coachVal.first_name + " " + coachVal.last_name
                    planObj['oriCoachName'] = coachName
                coachName = User.objects.get(id=planObj['plan_id__originalPlanner_id'])
                planObj['planDescription'] = str(
                    planObj['plan_id__planDescription']) + "<br><h6>Copyright &copy; 2017 " + str(
                    str(coachName.first_name) + " " + str(coachName.last_name)) + ". All rights reserved.</h6>"
            downloadUsers = UserPlan.objects.filter(plan_id=planObj['plan_id']).count()
            ratingObj = PlanRating.objects.filter(plan=planObj['plan_id']).values()
            totalRate = 0
            userCount = 1
            for rt in ratingObj:
                rateObj = dict(rt)
                totalRate = totalRate + rateObj['rating']
                userCount = userCount + 1
            rating = totalRate / userCount
            planObj['planPurpose'] = planAbilities
            planObj['plan_goals'] = planGoals
            planObj['planType'] = planObj['plan_id__programType__programTypeName']
            planObj['planCompetency'] = "0"
            planObj['planUsers'] = downloadUsers
            totalusercount = totalusercount + int(downloadUsers)
            planObj['PlanRating'] = rating
            planObj['coachId'] = planObj['plan_id__createdBy_id']
            planObj['createdBy'] = planObj['plan_id__createdBy_id']
            planObj['createdBy_id__avatar'] = planObj['plan_id__createdBy_id__avatar']
            planObj['indianIosPrice'] = planObj['plan_id__indianIosPrice']
            planObj['indianPrice'] = planObj['plan_id__indianPrice']
            planObj['iosPrice'] = planObj['plan_id__iosPrice']
            planObj['licencePolicy'] = planObj['plan_id__licencePolicy']
            planObj['originalPlanner_id'] = planObj['plan_id__originalPlanner_id']
            planObj['planName'] = planObj['plan_id__planName']
            planObj['id'] = planObj['plan_id']
            if planObj['planType'] == "STARTER":
                planObj['ptype'] = 'S'
            elif planObj['planType'] == "INTERMEDIATE":
                planObj['ptype'] = 'I'
            elif planObj['planType'] == "ADVANCED":
                planObj['ptype'] = 'A'

            if planObj['plan_id__planPhoto'] is not None:
                planObj['planPhoto'] = settings.S3URL + planObj['plan_id__planPhoto']
            else:
                planObj['planPhoto'] = planObj['plan_id__planPhoto']
            if planObj['plan_id__planLogo'] is not None:
                planObj['planLogo'] = settings.S3URL + planObj['plan_id__planLogo']
            else:
                planObj['planLogo'] = planObj['plan_id__planLogo']
            planObj['coachId'] = planObj['plan_id__createdBy_id']
            dataArr.append(planObj)
    return dataArr

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def getSessionDetails(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    dataReq = json.loads(request.body.decode('utf-8'))
    try:
        if username != None:
            userplans = []
            userPlanObj = UserPlan.objects.filter(user_id=dataReq['user_id'],id = dataReq['user_plan_id']).values()
            x = connection.cursor()
            count = 0
            sessions = []
            sess = []
            today = datetime.now()
            sessionStatus = 0
            if userPlanObj.exists():
                for dt in userPlanObj:
                    uPlan = dict(dt)
                    planId = uPlan['plan_id']
                    #print(uPlan)
                    userPlanID = uPlan['id']
                    userplans.append(userPlanID)
                    dayOff = uPlan['dayOff']
                    if dayOff == 0:
                        dayOff = 6
                    else:
                        dayOff = dayOff-1
                    sessStartDate = uPlan['startDate']
                planSessions = PlanSession.objects.select_related('Microcycle','PlanMesocycle','PlanPeriods','Plan').filter(microcycle__mesocycle__period__plan = dataReq['plan_id']).values().order_by('id')
                for pSess in planSessions:
                    #if today.strftime("%Y-%m-%d") <= sessStartDate.strftime("%Y-%m-%d"):
                    planSess = dict(pSess)
                    count = count + 1
                    doneSessions = UserSets.objects.filter(userplan_id__in = userplans,session_id = planSess['id']).values('session_id','createdDate','setDate','sessionStatus').order_by('createdDate').order_by('session_id')
                    planSess['skip'] = True
                    uploadedImages = CelebrityUploads.objects.select_related('UserSets').filter(userSet_id__session_id = planSess['id'],userSet_id__userplan_id__in = userplans,status = 1).values().order_by('-id')
                    planSess['images'] = []
                    if uploadedImages.exists():
                        for img in uploadedImages:
                            imgObj = dict(img)
                            if imgObj['imageUrl'] != '' and imgObj['imageUrl'] != None:
                                planSess['images'].append(imgObj['imageUrl'])
                    if planSess['images'] != []:
                        planSess['images'] = planSess['images'][:1]
                        planSess['images'] = " ".join(str(x) for x in planSess['images'])
                    if doneSessions.exists():
                        for ds in doneSessions:
                            dsObj = dict(ds)
                            sessionStatus = dsObj['sessionStatus']
                            planSess['sessionName'] = "Session " + str(count)
                            planSess['sessionDate'] = dsObj['setDate'].strftime("%Y-%m-%d")
                        planSess['skip'] = False
                    else:
                        planSess['skip'] = True
                        planSess['sessionName'] = "Session " + str(count)
                        planSess['sessionDate'] = ""
                    exerciseDetails = PlanExcercise.objects.select_related('Exercise').filter(session_id=planSess['id']).values('id', 'exerciseName__exerciseName', 'session','num_of_sets', 'extra_set', 'num_of_reps', 'intensity','createdDate', 'exerciseName_id')
                    planSess['exArr'] = []
                    if exerciseDetails.exists():
                        for ex in exerciseDetails:
                            exObj = dict(ex)
                            #exArr.append(valObj)
                            planSess['exArr'].append(exObj)
                    #print(sessStartDate.strftime("%Y-%m-%d")," ---------  ",today.strftime("%Y-%m-%d"))
                    #if today.strftime("%Y-%m-%d") >= sessStartDate.strftime("%Y-%m-%d"):
                    if planSess['skip'] == False:
                        if user==dataReq['user_id']:
                            sessions.append({'sessionId': planSess['sessionName'],"sessionDate": planSess['sessionDate'],"exArr": planSess['exArr'],"skip":planSess['skip'],"sessImage":planSess['images']})
                        elif sessionStatus == 1:
                            sessions.append({'sessionId': planSess['sessionName'], "sessionDate": planSess['sessionDate'],"exArr": planSess['exArr'], "skip": planSess['skip'],"sessImage": planSess['images']})
                sess+=reversed(sessions)
                return JsonResponse({"success": True, "details":sess})
            else:
                return JsonResponse({"success": False, "message": "No Active Plan"})
        else:
            return JsonResponse({"success": False, "message": "User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        #exceptionMail(user, req, url, str(e))

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def createPlanLikes(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    dataReq = json.loads(request.body.decode('utf-8'))
    try:
        if username != None:
            if 'review' in dataReq and dataReq['review'] !='':
                review = dataReq['review']
            else:
                review =''
            existplan = CelebrityPlansLikes.objects.values('id','plan_id','user_id','status','reviews').filter(plan_id =dataReq['planid'],user_id=user)
            if existplan.exists():
                for dt in existplan:
                    planObj = dict(dt)
                    details = CelebrityPlansLikes.objects.get(id=planObj['id'])
                    if 'status' in dataReq and dataReq['status'] != '':
                        details.status = dataReq['status']
                    #details.status = dataReq['status']
                    if details.reviews !='' and details.reviews is not None:
                        reviewstatus = 2
                    else:
                        reviewstatus = 1
                    if review !='':
                        details.reviews = review
                    details.save()
                    if details.status ==True:
                        status=1
                    else:
                        status = 0
                return JsonResponse({"success": True, "message": "Unliked","likeStatus":status, "status":reviewstatus})
            else:
                planlikes = CelebrityPlansLikes.objects.create(
                    plan_id = dataReq['planid'],
                    user_id = user,
                    #status = dataReq['status'],
                    reviews = review,
                )
                if 'status' in dataReq and dataReq['status'] != '':
                    planlikes.status = dataReq['status']
                planlikes.save()
                existlikes = CelebrityPlansLikes.objects.values('id', 'plan_id', 'user_id', 'status').filter(plan_id=dataReq['planid'], user_id=user)
                if existlikes.exists():
                    for dt1 in existlikes:
                        planlikeObj =dict(dt1)
                        if planlikeObj['plan_id'] == dataReq['planid'] and planlikeObj['user_id'] == user:
                            status = planlikeObj['status']
                return JsonResponse({"success": True, "message":"Liked","likeStatus":status, "status":1})
        else:
            return JsonResponse({"success": False, "message": "User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        #exceptionMail(user, req, url, str(e))

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def getcelebritydetails(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    try:
        if username != None:
            if username['userType'] == 8:
                celebrityArr=[]
                details = CelebrityDetails.objects.filter(userid_id=user).values()
                for dt in details:
                    celbObj = dict(dt)
                    celebrityArr.append(celbObj)
                return JsonResponse({"success": True,"celbdetails":celebrityArr})
        else:
            return JsonResponse({"success": False, "message": "User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        #exceptionMail(user, req, url, str(e))

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def createCelebrityDetails(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    user = username['id']
    dataReq = json.loads(request.body.decode('utf-8'))
    try:
        if username != None:
            clbdetails = CelebrityDetails.objects.filter(userid_id = user).values()
            if clbdetails.exists():
                for dt in clbdetails:
                    celbObj = dict(dt)
                    updatedetails = CelebrityDetails.objects.get(id=celbObj['id'])
                    updatedetails.designation = dataReq['occ']
                    updatedetails.about = dataReq['about']
                    updatedetails.favWorkout = dataReq['favwk']
                    updatedetails.userid_id = user
                    updatedetails.save()
                return JsonResponse({"success": True, "message": "Details updated Successfully"})
            else:
                details = CelebrityDetails.objects.create(
                    userid_id = user,
                    designation = dataReq['occ'],
                    about = dataReq['about'],
                    favWorkout = dataReq['favwk']
                )
                details.save()
                return JsonResponse({"success": True, "message":"Details saved Successfully"})
        else:
            return JsonResponse({"success": False, "message": "User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        #exceptionMail(user, req, url, str(e))

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def createCelebComments(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    dataReq = json.loads(request.body.decode('utf-8'))
    try:
        if username != None:
            if 'id' in dataReq and dataReq['id'] !='' and dataReq['id'] !=None:
                if 'status' in dataReq and dataReq['status'] != '':
                    deleteCeleb = CelebrityComments.objects.get(pk=dataReq['id'])
                    deleteCeleb.status=0
                    deleteCeleb.save()
                    return JsonResponse({"success": True, "message": "Comment Deleted Successfully"})
                else:
                    updateCeleb = CelebrityComments.objects.get(pk=dataReq['id'])
                    updateCeleb.comment = dataReq['comment']
                    updateCeleb.save()
                    return JsonResponse({"success": True, "message": "Comments Updated Successfully"})
            else:
                setId = UserSets.objects.get(userplan_id = dataReq['user_plan_id'],planexercise_id =dataReq['ex_id'],planset_id = dataReq['set_id'] )
                if setId:
                    createCelebrity = CelebrityComments.objects.create(
                        userset_id = setId.id,
                        celebrityId_id = username['id'],
                        createdBy_id = username['id'],
                        planId_id = dataReq['user_plan_id'],
                        comment = dataReq['comment'],
                    )
                    createCelebrity.save()
                return JsonResponse({"success": True, "message": "Comments 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))

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def updateSession(request):
    stratsessionutil = StartFitSessionUtil()
    username = stratsessionutil.get_user_insession(request)
    dataReq = json.loads(request.body.decode('utf-8'))
    try:
        if username != None:
            setId = UserSets.objects.filter(userplan_id = dataReq['user_plan_id'],user_id = username['id'],session_id = dataReq['session_id']).values('id')
            if setId.exists():
                for val in setId:
                    setObj = dict(val)
                    updateStatus = UserSets.objects.get(pk = setObj['id'])
                    updateStatus.sessionStatus = dataReq['status']
                    updateStatus.save()
            if dataReq['status'] == True:
                return JsonResponse({"success": True, "message": "Session Enabled Successfully"})
            else:
                return JsonResponse({"success": True, "message": "Session Disabled Successfully"})
        else:
            return JsonResponse({"success": False, "message": "User Logged Out"})
    except Exception as e:
        logger.exception("something wrong")
        #exceptionMail(user, req, url, str(e))