from django.shortcuts import render
from django.http import JsonResponse, HttpResponse, HttpResponseRedirect
from .models import customer, Matress, Physical_Age_Field, Physical_Age_Values, Age_analyze, Height_analyze, Weight_analyze, installer, Sender
from datetime import date
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from .email import Email
from decouple import config
import requests
import json
from django.views.decorators.clickjacking import xframe_options_exempt
from .ShopifyApi import Assets_Api
from django.conf import settings
import html
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent

# API_KEY = config('API_KEY')
# SHARED_SECRET = config('SHARED_SECRET')
# API_VERSION = config('API_VERSION')
# APP_URL = "dev.sleepezee.com"

API_KEY = '2bea07cbbdad54e61b2bc97336154ee8'
SHARED_SECRET = '864c0ec4d01c24eef80f4712fcfb6bff'
API_VERSION = '2023-07'
APP_URL = 'dev.sleepezee.com'

shop = ""
get_tkn = ""

################# APPLICATION SETUP ######################
# login page view functional code start (display template while go to main page) #
def login(request):
    return render(request, 'landing_page.html')
# login page view functional code end #

# generate token functional code start #
def token(code, shop):
    ''' GENERATE ACCESS_TOKEN '''
    ur = "https://" + shop + "/admin/oauth/access_token"

    s = {
        "client_id": API_KEY,
        "client_secret": SHARED_SECRET,
        "code": code
    }
    r = requests.post(url=ur, json=s)
    x = json.loads(r.text)
    return x
# generate token functional code end #

@csrf_exempt
def get_installation(url):
    s_url = url.strip('/')
    if ("https://" in s_url) or ("http://" in s_url):
        f_url = s_url
        api_key = API_KEY   
        link = '%s/admin/oauth/authorize?client_id=%s&redirect_uri=https://%s/final&scope=read_themes,write_themes' % (f_url, api_key, APP_URL)
        li = link.strip("/")
        redirect = HttpResponseRedirect(f'{li}')
    else: 
        f_url = "https://"+s_url
        api_key = API_KEY   
        link = '%s/admin/oauth/authorize?client_id=%s&redirect_uri=https://%s/final&scope=read_themes,write_themes' % (f_url, api_key, APP_URL)
        li = link.strip("/")
        redirect = HttpResponseRedirect(f'{li}')
    return redirect


# installation process functional code start #
@xframe_options_exempt
@csrf_exempt
def installation(request):
    redirect = ''
    if request.method == "POST":        # check request is post #
        url = request.POST.get('shop')
        s_url = url.strip('/')
        
        if ("https://" in s_url) or ("http://" in s_url):
            f_url = s_url
            api_key = API_KEY   
            link = '%s/admin/oauth/authorize?client_id=%s&redirect_uri=https://%s/final&scope=read_themes,write_themes' % (f_url, api_key, APP_URL)
            li = link.strip("/")
            redirect = HttpResponseRedirect(f'{li}')
        else: 
            f_url = "https://"+s_url
            api_key = API_KEY   
            link = '%s/admin/oauth/authorize?client_id=%s&redirect_uri=https://%s/final&scope=read_themes,write_themes' % (f_url, api_key, APP_URL)
            li = link.strip("/")
            redirect = HttpResponseRedirect(f'{li}')  
    return redirect
# installation process functional code end #

# redirect to app fucntional code start (while successfully installed redirect to app) #
def redirect(request):
    if request.GET.get('shop') is not None:     # check request data is not none #
        shop = request.GET.get('shop')
        redir = HttpResponseRedirect(redirect_to='https://' + shop + '/admin/apps/sleepzee-custom-app')
    return redir
# redirect to app fucntional code end #

# Uninstall Webhook functional code start (to create webhook) #
def unistaller_second(request):
    if len(shop) != 0:              # check the length of shop #
        webrec = installer.objects.filter(shop=shop)        # filter installer data by shop#
        if webrec:
            token = webrec[0].access_token
            hmac_data = webrec[0].hmac
        else:
            HttpResponse("Invalid shop detail")

        url = "https://" + shop + "/admin/api/2020-07/webhooks.json"

        headers = {
            'X-Shopify-Access-Token': token,
            'X-Shopify-Topic': 'app/uninstalled',
            'X-Shopify-Hmac-Sha256': hmac_data,
            'X-Shopify-Shop-Domain': shop,
            'X-Shopify-API-Version': API_VERSION
        } 

        my = {
            "webhook": {
                "topic": "app/uninstalled",
                "address": 'https://%s/uninstall'%(config("tunnel", default='dev.sleepezee.com')),  # uninstall process data send on the address #
                "format": "json"
            }
        }
    
        r = requests.post(url=url, json=my, headers=headers)
        c = json.loads(r.text)
        return HttpResponse(json.dumps(c), content_type="application/json")
# Uninstall Webhook functional code start

# app install final step functional code start (to add shop data into database) #
@xframe_options_exempt
def final(request):
    if request.GET.get('hmac') is not None:         # check hmac is not none #
        hmac = request.GET.get('hmac')
        host = request.GET.get('host')
        global shop
        shop = request.GET.get('shop')
        # with open(BASE_DIR /"print_output.txt", "a") as f:
        #     print(hmac,"hmac ....144", file=f)
        #     print(shop,"shop ....145", file=f) 
        #     print(request.GET.get('code')," request.GET.get('code')", file=f)
        #     print("------------------------", file=f)
        if request.GET.get('code') is not None:     # check code is not none #
            code = request.GET.get('code')
            
            if len(code) != 0:              # check length of code #
                record = installer.objects.filter(shop=shop)    # filter installer data by shop #
                if record:
                    shop = record[0].shop
                    get_tkn = record[0].access_token
                    return redirect(request=request)
                else:
                    accesstoken = token(code=code, shop=shop)       # call token function to generate access_token #
                    
                    get_owner_email = Assets_Api.get_email(shop=shop, token=accesstoken['access_token'])
                    if 'owner_email' in get_owner_email:
                        get_owner_email = get_owner_email["owner_email"]
                    else:
                        return HttpResponse("Didn't Fecthed Owner Email")
                    
                    rec = installer()           # call installer to add record #
                    rec.shop = shop
                    rec.code = code
                    rec.hmac = hmac
                    rec.host = host
                    rec.admin_email = get_owner_email
                    rec.access_token = accesstoken['access_token']
                    rec.save()      # save data in installer table #
                    
                    # ######## CALL ASSETS API HERE ###############
                    # data = Assets_Api.get_theme(shop=shop, token=accesstoken['access_token'])
                    # if data:
                    #     # call set_css function #
                    #     Assets_Api.set_css(shop=shop, token=accesstoken['access_token'], theme_id=data["themes"][0]["id"])

                    #     # # call set_js function #
                    #     Assets_Api.set_js(shop=shop, token=accesstoken['access_token'], theme_id=data["themes"][0]["id"])

                    #     # call set_section function8developer3i@gmail.com
                    #     Assets_Api.set_liquid(shop=shop, token=accesstoken['access_token'], theme_id=data["themes"][0]["id"])
                    
                    unistaller_second(request=request)          # call 'unistaller_second' to create webhook #
                    return redirect(request=request)            # redirect to app #
                return redirect(request=request)
        else:
            record = installer.objects.filter(shop=shop)        # filter installer data by shop #    
            if record:
                getaccess = record[0].access_token
                getshop = record[0].shop
                gethost = record[0].host
                # with open(BASE_DIR /"print_output.txt", "a") as f:
                #     print(record ,"record in else 195", file=f)
                #     print("------------------------", file=f)
                #     print(getshop,"getshop ....144", file=f)
                #     print(gethost,"gethost ....145", file=f)
                return render(request, 'index.html', {"shop":getshop, "host":gethost})
            else:
                return get_installation(shop)
    else:
        return render(request, 'login.html')


def theme_api(request):
    if request.method == "GET":
        shop = request.GET.get("shop")
        print(shop)
        check_shop = installer.objects.filter(shop=shop)
        print(check_shop)
        if check_shop:
            data = Assets_Api.get_theme(shop=check_shop[0].shop, token=check_shop[0].access_token)
            # for x in data["themes"]:
            print(data["themes"])
            return JsonResponse({"themes":data["themes"]})
        else:
            return HttpResponse("shop invalid")
        
@csrf_exempt
def theme_integration(request):
    if request.method == "POST":
        shop = request.POST.get("shop")
        shop_get = request.GET.get("shop")
        all_data = request.POST
        # with open(BASE_DIR /"print_output.txt", "a") as f:
        #     print(all_data,"all_data ....183", file=f)
        #     print(shop,"shop ....184", file=f)
        #     print(shop_get,"shop_get...185", file=f)
        #     print("------------------------", file=f)
        theme_id = request.POST.get("theme_id")

        check_shop = installer.objects.filter(shop=shop)
        print(check_shop)
        if check_shop:
            data = Assets_Api.get_theme(shop=check_shop[0].shop, token=check_shop[0].access_token)
            print(data["themes"][1]["id"], "id")
            Assets_Api.set_css(shop=check_shop[0].shop, token=check_shop[0].access_token, theme_id=theme_id)

            # # call set_js function #
            Assets_Api.set_js(shop=check_shop[0].shop, token=check_shop[0].access_token, theme_id=theme_id)

            # call set_section function8developer3i@gmail.com
            Assets_Api.set_liquid(shop=check_shop[0].shop, token=check_shop[0].access_token, theme_id=theme_id)
            return JsonResponse({"status:success"})
        else:
            return HttpResponse("shop invalid")
    

# app install final step functional code end #

def get_data(shop, type):
    data_dict = {}
    check_shop = installer.objects.filter(shop=shop)
   
    if check_shop:
        if type == "customerdata":
            user_list = []
            alluser = ''
            
            alluser = customer.objects.filter(shop=check_shop[0].id)
            for x in alluser:
                sub_user_dict = {
                    "id" :x.pk,
                    "name":x.name,
                    "contactNumber" : x.contact_number,
                    "city":x.city,
                    "email" :x.email,
                    "age" :x.age,
                    "gender" : x.gender,
                    "height": x.height,
                    "weight":x.weight
                }
                user_list.append(sub_user_dict)
            data_dict["customerdata"] = user_list
            data_dict["shop"] = check_shop[0].shop
        elif  type == "matress":
            matress_list = []
            allmatress = ''
            
            allmatress = Matress.objects.filter(shop=check_shop[0].id)
            for x in allmatress:
                sub_matress_dict = {
                    "id" :x.pk,
                    "matressfor":x.matressfor,
                    "getting_out_of_bed":x.getting_out_of_bed,
                    "driving_and_sitting_in_a_car_or_bus":x.driving_and_sitting_in_a_car_or_bus,
                    "climbing_15_to_20_stairs":x.climbing_15_to_20_stairs,
                    "lifting_and_carrying_bag_luggage":x.lifting_and_carrying_bag_luggage,
                }
                matress_list.append(sub_matress_dict)
            data_dict["matress"] = matress_list
            data_dict["shop"] = check_shop[0].shop        
        else:
            customer_list = []
            allcustomer = ''
            allcustomer = customer.objects.filter(shop=check_shop[0].id)
            for x in allcustomer:
                matressfor=''
                getting_out_of_bed = ''
                driving_and_sitting_in_a_car_or_bus = ''
                climbing_15_to_20_stairs = ''
                lifting_and_carrying_bag_luggage= ''
                matress_detail = Matress.objects.filter(customer_id=x.id)
                if matress_detail:
                    matressfor = matress_detail[0].matressfor
                    getting_out_of_bed = matress_detail[0].getting_out_of_bed
                    driving_and_sitting_in_a_car_or_bus = matress_detail[0].driving_and_sitting_in_a_car_or_bus
                    climbing_15_to_20_stairs = matress_detail[0].climbing_15_to_20_stairs
                    lifting_and_carrying_bag_luggage = matress_detail[0].lifting_and_carrying_bag_luggage
                else:
                    matressfor=''
                    getting_out_of_bed = ''
                    driving_and_sitting_in_a_car_or_bus = ''
                    climbing_15_to_20_stairs = ''
                    lifting_and_carrying_bag_luggage = ''

                sub_customer_dict = {
                    "id":x.id,
                    "name" : x.name,
                    "contactNumber" : x.contact_number,
                    "city": x.city,
                    "email": x.email,
                    "gender": x.gender,
                    "age": x.age,
                    "height": x.height,
                    "weight": x.weight,
                    "date": x.date,
                    "getting_out_of_bed":getting_out_of_bed,
                    "driving_and_sitting_in_a_car_or_bus":driving_and_sitting_in_a_car_or_bus ,
                    "climbing_15_to_20_stairs":climbing_15_to_20_stairs,
                    "lifting_and_carrying_bag_luggage":lifting_and_carrying_bag_luggage,
                    "matressfor":matressfor,
                }
                
                customer_list.append(sub_customer_dict)
            data_dict["customer"] = customer_list
            data_dict["shop"] = check_shop[0].shop
    else:
        data_dict["message"] = "Invalid Shop Detail"
    return data_dict

def get_customer_internal(request):
    if request.method == "GET":
        with open(BASE_DIR /"print_output.txt", "a") as f:
            print("in get_customer_internal", file=f)
            print(request.GET.get("type"),"------------------------", file=f)
            print(request.GET.get("shop"),"------------------------", file=f)
        shop_name= request.GET.get("shop")
        type_n = request.GET.get("type")
        data = get_data(shop=shop_name, type=type_n)
        return JsonResponse(data)

    
# http://127.0.0.1:8000/matress/smtp_data/?shop=3istore.myshopify.com&type=smtpdetails
def smtp_data(shop, type, id=None):
    smtp_dict = {}
    check_shop = installer.objects.filter(shop=shop)
    if check_shop:
        if type == "smtpdetails":
            smtp_list = []
            allsmtp = ''
            if id is not None:
                allsmtp = Sender.objects.all().filter(id=id)
            else:
                allsmtp = Sender.objects.all().filter(smtp_shop=check_shop[0].id)
            for x in allsmtp:
                sub_smtp_dict = {
                    "smtp_host":x.smtp_host,
                    "smtp_port":x.smtp_port,
                    "smtp_username":x.smtp_username,
                    "smtp_password":x.smtp_password,
                    "use_tls":x.use_tls,
                    "spine_soft_template_user" :x.spine_soft_template_user,
                    "spine_soft_subject_user" : x.spine_soft_subject_user,
                    "spine_medium_template_user":x.spine_medium_template_user,
                    "spine_medium_subject_user":x.spine_medium_subject_user,
                    "spine_firm_template_user":x.spine_firm_template_user,
                    "spine_firm_subject_user":x.spine_firm_subject_user,
                    "spine_xfirm_template_user":x.spine_xfirm_template_user,
                    "spine_xfirm_subject_user":x.spine_xfirm_subject_user,
                    "spine_soft_template_admin":x.spine_soft_template_admin,
                    "spine_soft_subject_admin":x.spine_soft_subject_admin,
                    "spine_medium_template_admin":x.spine_medium_template_admin,
                    "spine_medium_subject_admin":x.spine_medium_subject_admin,
                    "spine_firm_template_admin":x.spine_firm_template_admin,
                    "spine_firm_subject_admin":x.spine_firm_subject_admin,
                    "spine_xfirm_template_admin":x.spine_xfirm_template_admin,
                    "spine_xfirm_subject_admin":x.spine_xfirm_subject_admin,
                    }
                smtp_list.append(sub_smtp_dict)
            smtp_dict["smtpdetails"] = smtp_list
            smtp_dict["shop"] = check_shop[0].shop 
        else:
            smtp_d_list = []
            allsmtpdetails = Sender.objects.all()
            for x in allsmtpdetails:
                smtp_sub_dict = {
                    "smtp_host":x.smtp_host,
                    "smtp_port":x.smtp_port,
                    "smtp_username":x.smtp_username,
                    "smtp_password":x.smtp_password,
                    "use_tls":x.use_tls,
                    "spine_soft_template_user" :x.spine_soft_template_user,
                    "spine_soft_subject_user" : x.spine_soft_subject_user,
                    "spine_medium_template_user":x.spine_medium_template_user,
                    "spine_medium_subject_user":x.spine_medium_subject_user,
                    "spine_firm_template_user":x.spine_firm_template_user,
                    "spine_firm_subject_user":x.spine_firm_subject_user,
                    "spine_xfirm_template_user":x.spine_xfirm_template_user,
                    "spine_xfirm_subject_user":x.spine_xfirm_subject_user,
                    "spine_soft_template_admin":x.spine_soft_template_admin,
                    "spine_soft_subject_admin":x.spine_soft_subject_admin,
                    "spine_medium_template_admin":x.spine_medium_template_admin,
                    "spine_medium_subject_admin":x.spine_medium_subject_admin,
                    "spine_firm_template_admin":x.spine_firm_template_admin,
                    "spine_firm_subject_admin":x.spine_firm_subject_admin,
                    "spine_xfirm_template_admin":x.spine_xfirm_template_admin,
                    "spine_xfirm_subject_admin":x.spine_xfirm_subject_admin,
                    } 
                smtp_d_list.append(smtp_sub_dict)
            smtp_dict["smtpdetails"] = smtp_list
            smtp_dict["shop"] = check_shop[0].shop   
    else:
        smtp_dict["message"]= "Invalid smtp details"
    return smtp_dict

def get_smtp_details(request,id=None):
    if request.method == "GET":
        shop = request.GET.get("shop")
        type = request.GET.get("type") 
        data = smtp_data(shop=shop, type=type, id=id)
        return JsonResponse(data)

# http://127.0.0.1:8000/matress/smtp_details/?shop=3istore.myshopify.com
@csrf_exempt
def save_smtp_details(request):
    if request.method == 'POST':
        shop = request.POST.get('shop')
        all_data = request.POST
        # with open(BASE_DIR /"print_output.txt", "a") as f:
        #     print("...............................................", file=f)
        #     print(all_data,"all_data ....404", file=f)
        #     print(shop,"shop ....405", file=f)
        check_shop = installer.objects.filter(shop=shop)
        if check_shop:
            smtp_host = request.POST.get('smtpHost')
            smtp_port=request.POST.get('smtpPort')   
            smtp_username=request.POST.get('smtpUser')
            smtp_password=request.POST.get('smtpPassword')
            use_tls=request.POST.get('smtpUseTLS')
            spine_soft_template_user = request.POST.get('softTemplateUser')
            spine_soft_subject_user = request.POST.get('softSubjectUser')
            spine_medium_template_user = request.POST.get('mediumTemplateUser')
            spine_medium_subject_user = request.POST.get('mediumSubjectUser')
            spine_firm_template_user = request.POST.get('firmTemplateUser')
            spine_firm_subject_user = request.POST.get('firmSubjectUser')
            spine_xfirm_template_user = request.POST.get('xFirmTemplateUser')
            spine_xfirm_subject_user = request.POST.get('xFirmSubjectUser')
            spine_soft_template_admin = request.POST.get('softTemplateAdmin')
            spine_soft_subject_admin = request.POST.get('softSubjectAdmin')
            spine_medium_template_admin = request.POST.get('mediumTemplateAdmin')
            spine_medium_subject_admin = request.POST.get('mediumSubjectAdmin')
            spine_firm_template_admin = request.POST.get('firmTemplateAdmin')
            spine_firm_subject_admin = request.POST.get('firmSubjectAdmin')
            spine_xfirm_template_admin  = request.POST.get('xFirmTemplateAdmin')
            spine_xfirm_subject_admin = request.POST.get('xFirmSubjectAdmin')

            smtp_data = Sender.objects.filter(smtp_shop_id = check_shop[0].id)
            if smtp_data:
                chenge = Sender.objects.filter(smtp_shop_id =  check_shop[0].id).update(smtp_host=smtp_host,smtp_port=smtp_port,smtp_username=smtp_username,smtp_password=smtp_password,use_tls=use_tls,spine_soft_template_user = spine_soft_template_user,spine_soft_subject_user = spine_soft_subject_user,spine_medium_template_user=spine_medium_template_user,spine_medium_subject_user=spine_medium_subject_user,spine_firm_template_user=spine_firm_template_user,spine_firm_subject_user=spine_firm_subject_user,spine_xfirm_template_user=spine_xfirm_template_user,spine_xfirm_subject_user=spine_xfirm_subject_user,spine_soft_template_admin=spine_soft_template_admin,spine_soft_subject_admin=spine_soft_subject_admin,spine_medium_template_admin=spine_medium_template_admin,spine_medium_subject_admin=spine_medium_subject_admin,spine_firm_template_admin=spine_firm_template_admin,spine_firm_subject_admin = spine_firm_subject_admin,spine_xfirm_template_admin=spine_xfirm_template_admin,spine_xfirm_subject_admin = spine_xfirm_subject_admin)
                return HttpResponse("Sender details update  successfully!")
            else:
                sender = Sender(smtp_host=smtp_host,smtp_port=smtp_port,smtp_username=smtp_username,smtp_password=smtp_password,use_tls=use_tls,smtp_shop_id = check_shop[0].id,spine_soft_template_user = spine_soft_template_user,spine_soft_subject_user = spine_soft_subject_user,spine_medium_template_user=spine_medium_template_user,spine_medium_subject_user=spine_medium_subject_user,spine_firm_template_user=spine_firm_template_user,spine_firm_subject_user=spine_firm_subject_user,spine_xfirm_template_user=spine_xfirm_template_user,spine_xfirm_subject_user=spine_xfirm_subject_user,spine_soft_template_admin=spine_soft_template_admin,spine_soft_subject_admin=spine_soft_subject_admin,spine_medium_template_admin=spine_medium_template_admin,spine_medium_subject_admin=spine_medium_subject_admin,spine_firm_template_admin=spine_firm_template_admin,spine_firm_subject_admin = spine_firm_subject_admin,spine_xfirm_template_admin=spine_xfirm_template_admin,spine_xfirm_subject_admin = spine_xfirm_subject_admin)
                sender.save()
                # with open(BASE_DIR /"print_output.txt", "a") as f:
                #     print("...............................................", file=f)
                #     print(sender,"sender ....436", file=f)
                #     print(sender.pk,"sender ....437", file=f)
                return HttpResponse("Sender details saved successfully!")
        else:
            return HttpResponse("Shop not found!")
    else:
        shop = request.GET.get("shop")
        return render(request, 'smtp.html',{"shop":shop})
    
@csrf_exempt
def matress_details(request):
    # with open(BASE_DIR /"print_output.txt", "a") as f:
    #     print("...............................................", file=f)
    #     print(request.method,"request.method ....", file=f)
    #     print(request.POST,"request.POST ....", file=f)
    #     print(request.GET,"request.GET ....", file=f)
    if request.method == "POST":
        shop = request.POST.get("shop")
        check_shop = installer.objects.filter(shop=shop)
        if check_shop:
            name = request.POST.get('name')
            contact_number = request.POST.get('contactNumber')
            city = request.POST.get('city')
            email = request.POST.get('email')
            gender = request.POST.get('gender')
            age = request.POST.get('age')
            height = request.POST.get('height')
            weight = request.POST.get('weight')
            getting_out_of_bed = request.POST.get("getting_out_of_bed")
            driving_and_sitting_in_a_car_or_bus = request.POST.get("driving_and_sitting_in_a_car_or_bus")
            climbing_15_to_20_stairs = request.POST.get("climbing_15_to_20_stairs")
            lifting_and_carrying_bag_luggage = request.POST.get("lifting_and_carrying_bag_luggage")
            matressfor = request.POST.get("matressfor")
            
            customer_data = customer(
                    name=name,
                    contact_number=contact_number,
                    city=city,
                    email=email,
                    gender=gender,
                    age=age,
                    height=height,
                    weight=weight,
                    date= date,
                    shop_id= check_shop[0].id
                    )
            
            customer_data.save()
                
            if customer_data:
                    matress_data = Matress(
                        matressfor=matressfor,
                        getting_out_of_bed=getting_out_of_bed,
                        driving_and_sitting_in_a_car_or_bus=driving_and_sitting_in_a_car_or_bus,
                        climbing_15_to_20_stairs=climbing_15_to_20_stairs,
                        lifting_and_carrying_bag_luggage=lifting_and_carrying_bag_luggage,
                        customer_id = customer_data.id,
                        shop_id = check_shop[0].id  
                    )
            matress_data.save()

            
            # Analyze Result #
            matress_list = []
            avg_result = {}
            final_result = []
            result_dict = {}
            id = customer_data.id
            if id:
                data = get_data(shop=check_shop[0].shop, type="submission")
                matress_list.append(data)
            else:
                data = get_data(shop=check_shop[0].shop, type="submission")
                matress_list.append(data)

            
            # weight
            if matress_list:
                for item in matress_list:
                    item_dict = item
                   
                    c_customer = item_dict['customer']

                    spine_soft = []
                    spine_medium = []
                    spine_firm = []
                    spine_xfirm = []

                    # height
                    height = 110 if (c_customer[0]['height'] < 110) else c_customer[0]['height'] 
                    height_avg_ss = Height_analyze.objects.get(height=height).spine_soft
                    height_avg_sm = Height_analyze.objects.get(height=height).spine_medium
                    height_avg_sf = Height_analyze.objects.get(height=height).spine_firm
                    height_avg_sx = Height_analyze.objects.get(height=height).spine_xfirm
                    
                    if height_avg_ss:
                        spine_soft.append(height_avg_ss)
                    if height_avg_sm:
                        spine_medium.append(height_avg_sm)
                    if height_avg_sf:
                        spine_firm.append(height_avg_sf)
                    if height_avg_sx:
                        spine_xfirm.append(height_avg_sx)

                    # age
                    age = 20 if (c_customer[0]['age'] < 20) else c_customer[0]['age'] 
                    age_avg_ss = Age_analyze.objects.get(Age=age).spine_soft
                    age_avg_sm = Age_analyze.objects.get(Age=age).spine_medium
                    age_avg_sf = Age_analyze.objects.get(Age=age).spine_firm
                    age_avg_sx = Age_analyze.objects.get(Age=age).spine_xfirm
                    
                    if age_avg_ss:
                        spine_soft.append(age_avg_ss)
                    if age_avg_sm:
                        spine_medium.append(age_avg_sm)
                    if age_avg_sf:
                        spine_firm.append(age_avg_sf)
                    if age_avg_sx:
                        spine_xfirm.append(age_avg_sx)
                    

                    # weight
                    weight = 40 if (c_customer[0]['weight'] < 40) else c_customer[0]['weight'] 
                    weight_avg_ss = Weight_analyze.objects.get(weight=weight).spine_soft
                    weight_avg_sm = Weight_analyze.objects.get(weight=weight).spine_medium
                    weight_avg_sf = Weight_analyze.objects.get(weight=weight).spine_firm
                    weight_avg_sx = Weight_analyze.objects.get(weight=weight).spine_xfirm
                    
                    if weight_avg_ss:
                        spine_soft.append(weight_avg_ss)
                    if weight_avg_sm:
                        spine_medium.append(weight_avg_sm)
                    if weight_avg_sf:
                        spine_firm.append(weight_avg_sf)
                    if weight_avg_sx:
                        spine_xfirm.append(weight_avg_sx)

                    # physical age  
                    phy_age_ss = []
                    phy_age_sm = []
                    phy_age_sf = []
                    phy_age_sx = []

                    phy_age_g_id = Physical_Age_Field.objects.get(field_name="getting_out_of_bed", field_value=c_customer[0]['getting_out_of_bed']).id
                    phy_age_g_value_ss = Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_g_id).spine_soft
                    phy_age_g_value_sm = Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_g_id).spine_medium
                    phy_age_g_value_sf = Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_g_id).spine_firm
                    phy_age_g_value_sx = Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_g_id).spine_xfirm
                    if phy_age_g_value_ss:
                        phy_age_ss.append(float(phy_age_g_value_ss))
                    if phy_age_g_value_sm:
                        phy_age_sm.append(phy_age_g_value_sm)
                    if phy_age_g_value_sf:
                        phy_age_sf.append(phy_age_g_value_sf)
                    if phy_age_g_value_sx:
                        phy_age_sx.append(phy_age_g_value_sx)

                    phy_age_d_id = Physical_Age_Field.objects.get(field_name="driving_and_sitting_in_a_car_or_bus", field_value=c_customer[0]['driving_and_sitting_in_a_car_or_bus']).id
                    phy_age_d_value_ss = Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_d_id).spine_soft
                    phy_age_d_value_sm = Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_d_id).spine_medium
                    phy_age_d_value_sf = Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_d_id).spine_firm
                    phy_age_d_value_sx = Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_d_id).spine_xfirm
                    if phy_age_d_value_ss:
                        phy_age_ss.append(float(phy_age_d_value_ss))
                    if phy_age_d_value_sm:
                        phy_age_sm.append(phy_age_d_value_sm)
                    if phy_age_d_value_sf:
                        phy_age_sf.append(phy_age_d_value_sf)
                    if phy_age_d_value_sx:
                        phy_age_sx.append(phy_age_d_value_sx)
                    
                    phy_age_c_id = Physical_Age_Field.objects.get(field_name="climbing_15_to_20_stairs", field_value=c_customer[0]['climbing_15_to_20_stairs']).id
                    phy_age_c_value_ss = Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_c_id).spine_soft
                    phy_age_c_value_sm = Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_c_id).spine_medium
                    phy_age_c_value_sf = Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_c_id).spine_firm
                    phy_age_c_value_sx = Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_c_id).spine_xfirm
                    if phy_age_c_value_ss:
                        phy_age_ss.append(float(phy_age_c_value_ss))
                    if phy_age_c_value_sm:
                        phy_age_sm.append(phy_age_c_value_sm)
                    if phy_age_c_value_sf:
                        phy_age_sf.append(phy_age_c_value_sf)
                    if phy_age_c_value_sx:
                        phy_age_sx.append(phy_age_c_value_sx)

                    phy_age_l_id = Physical_Age_Field.objects.get(field_name="lifting_and_carrying_bag_luggage", field_value=c_customer[0]['lifting_and_carrying_bag_luggage']).id
                    phy_age_l_value_ss = Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_l_id).spine_soft
                    phy_age_l_value_sm= Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_l_id).spine_medium
                    phy_age_l_value_sf = Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_l_id).spine_firm
                    phy_age_l_value_sx = Physical_Age_Values.objects.get(Physical_Age_Field_id = phy_age_l_id).spine_xfirm
                    if phy_age_l_value_ss:
                        phy_age_ss.append(float(phy_age_l_value_ss))
                    if phy_age_l_value_sm:
                        phy_age_sm.append(phy_age_l_value_sm)
                    if phy_age_l_value_sf:
                        phy_age_sf.append(phy_age_l_value_sf)
                    if phy_age_l_value_sx:
                        phy_age_sx.append(phy_age_l_value_sx)
            
                    spine_soft.append(round(Average(phy_age_ss),2))
                    spine_medium.append(round(Average(phy_age_sm),2))
                    spine_firm.append(round(Average(phy_age_sf),2))
                    spine_xfirm.append(round(Average(phy_age_sx),2))
                    avg_result['spine_soft'] = round(Average(spine_soft),2)
                    avg_result['spine_medium'] = round(Average(spine_medium),2)
                    avg_result['spine_firm'] = round(Average(spine_firm),2)
                    avg_result['spine_xfirm'] = round(Average(spine_xfirm),2)
                    
                    c_customer[0]['result']=avg_result
                   
                    for x in c_customer:
                        sub_dict = {
                            "id": x["id"],
                            "name": x["name"],
                            "contactNumber": x["contactNumber"],
                            "city": x["city"],
                            "email": x["email"],
                            "gender": x["gender"],
                            "age": x["age"],
                            "height": x["height"],
                            "weight": x["weight"],
                            "date": x["date"],
                            "getting_out_of_bed":x["getting_out_of_bed"],
                            "driving_and_sitting_in_a_car_or_bus": x["driving_and_sitting_in_a_car_or_bus"],
                            "climbing_15_to_20_stairs": x["climbing_15_to_20_stairs"],
                            "lifting_and_carrying_bag_luggage": x["lifting_and_carrying_bag_luggage"],
                            "matressfor":x["matressfor"],
                            "result": x["result"]
                        }
                        final_result.append(sub_dict)
                
                result_dict["customer"] = final_result
                max_key = max(avg_result, key=avg_result.get)

                # with open(BASE_DIR /"print_output.txt", "a") as f:
                #     print("...............................................", file=f)
                #     print(result_dict,"result_dict ....", file=f)
                #     print("result_dict  ....", file=f)
                Email.email_user(customer=result_dict, to=email, shop=shop, max_result=max_key)
                Email.email_admin(customer=result_dict, shop=shop, max_result=max_key)
                
        
                return JsonResponse(result_dict) 
        else:
            return HttpResponse('shop is not available')
    # else:
    #     shop = request.GET.get("shop")
    #     return render(request, 'index_dhara.html', {"shop":shop})
    
def Average(lst):
    return sum(lst) / len(lst)

# http://127.0.0.1:8000/matress/send_email/10?shop=3istore.myshopify.com
# http://127.0.0.1:8000/matress/send_email/?shop=3istore.myshopify.com
def email_configs(request, sender_id=None):
    if request.method == "GET":
        shop = request.GET.get('shop')
        smtp_host = ''
        smtp_port = ''
        smtp_username = ''
        smtp_password = ''
        use_tls = ''
        spine_soft_template_user = ''
        spine_soft_subject_user = ''
        spine_medium_template_user = ''
        spine_medium_subject_user = ''
        spine_firm_template_user = ''
        spine_firm_subject_user = ''
        spine_xfirm_template_user = ''
        spine_xfirm_subject_user = ''
        spine_soft_template_admin = ''
        spine_soft_subject_admin = ''
        spine_medium_template_admin = ''
        spine_medium_subject_admin = ''
        spine_firm_template_admin = ''
        spine_firm_subject_admin = ''
        spine_xfirm_template_admin = ''
        spine_xfirm_subject_admin = ''

        check_shop = installer.objects.filter(shop=shop)
        if check_shop != []:
            if sender_id is not None:
                sender = ''
                try:
                    sender = Sender.objects.get(pk=sender_id)
                    spine_soft_template_user= html.escape(spine_soft_template_user,quote=True)
                    spine_soft_subject_user = spine_soft_subject_user
                    spine_medium_template_user =html.escape(spine_medium_template_user,quote=True)
                    spine_medium_subject_user = spine_medium_subject_user
                    spine_firm_template_user = html.escape(spine_firm_template_user,quote=True)
                    spine_firm_subject_user = spine_firm_subject_user
                    spine_xfirm_template_user = html.escape(spine_xfirm_template_user,quote=True)
                    spine_xfirm_subject_user = spine_xfirm_subject_user
                    spine_soft_template_admin = html.escape(spine_soft_template_admin,quote=True)
                    spine_soft_subject_admin = spine_soft_subject_admin
                    spine_medium_template_admin = html.escape(spine_medium_template_admin,quote=True)
                    spine_medium_subject_admin = spine_medium_subject_admin
                    spine_firm_template_admin = html.escape(spine_firm_template_admin,quote=True)
                    spine_firm_subject_admin = spine_firm_subject_admin
                    spine_xfirm_template_admin = html.escape(spine_xfirm_template_admin,quote=True)
                    spine_xfirm_subject_admin = spine_xfirm_subject_admin

                except Sender.DoesNotExist:
                    smtp_host = settings.EMAIL_HOST
                    smtp_port = settings.EMAIL_PORT
                    smtp_username = settings.EMAIL_HOST_USER
                    smtp_password = settings.EMAIL_HOST_PASSWORD
                    use_tls = settings.EMAIL_USE_TLS
                smtp_host = sender.smtp_host
                smtp_port = sender.smtp_port
                smtp_username = sender.smtp_username
                smtp_password = sender.smtp_password
                use_tls = sender.use_tls
                spine_soft_template_user = html.escape(sender.spine_soft_template_user,quote=True)
                spine_soft_subject_user = sender.spine_soft_subject_user
                spine_medium_template_user = html.escape(sender.spine_medium_template_user,quote=True)
                spine_medium_subject_user = sender.spine_medium_subject_user
                spine_firm_template_user = html.escape(sender.spine_firm_template_user,quote=True)
                spine_firm_subject_user = sender.spine_firm_subject_user
                spine_xfirm_template_user = html.escape(sender.spine_xfirm_template_user,quote=True) 
                spine_xfirm_subject_user = sender.spine_xfirm_subject_user
                spine_soft_template_admin = html.escape(sender.spine_soft_template_admin,quote=True)
                spine_soft_subject_admin = sender.spine_soft_subject_admin
                spine_medium_template_admin = html.escape(sender.spine_medium_template_admin,quote=True)
                spine_medium_subject_admin = sender.spine_medium_subject_admin
                spine_firm_template_admin = html.escape(sender.spine_firm_template_admin,quote=True)
                spine_firm_subject_admin = sender.spine_firm_subject_admin
                spine_xfirm_template_admin = html.escape(sender.spine_xfirm_template_admin,quote=True)
                spine_xfirm_subject_admin = sender.spine_xfirm_subject_admin


            else:
                sender = ''
                try:
                    sender = Sender.objects.get(smtp_shop_id = check_shop[0].id)
                    spine_soft_template_user= html.escape(spine_soft_template_user,quote=True)
                    spine_soft_subject_user = spine_soft_subject_user
                    spine_medium_template_user =html.escape(spine_medium_template_user,quote=True)
                    spine_medium_subject_user = spine_medium_subject_user
                    spine_firm_template_user = html.escape(spine_firm_template_user,quote=True)
                    spine_firm_subject_user = spine_firm_subject_user
                    spine_xfirm_template_user = html.escape(spine_xfirm_template_user,quote=True)
                    spine_xfirm_subject_user = spine_xfirm_subject_user
                    spine_soft_template_admin = html.escape(spine_soft_template_admin,quote=True)
                    spine_soft_subject_admin = spine_soft_subject_admin
                    spine_medium_template_admin = html.escape(spine_medium_template_admin,quote=True)
                    spine_medium_subject_admin = spine_medium_subject_admin
                    spine_firm_template_admin = html.escape(spine_firm_template_admin,quote=True)
                    spine_firm_subject_admin = spine_firm_subject_admin
                    spine_xfirm_template_admin = html.escape(spine_xfirm_template_admin,quote=True)
                    spine_xfirm_subject_admin = spine_xfirm_subject_admin
                except Sender.DoesNotExist:
                    smtp_host = settings.EMAIL_HOST
                    smtp_port = settings.EMAIL_PORT
                    smtp_username = settings.EMAIL_HOST_USER
                    smtp_password = settings.EMAIL_HOST_PASSWORD
                    use_tls = settings.EMAIL_USE_TLS
                smtp_host = sender.smtp_host
                smtp_port = sender.smtp_port
                smtp_username = sender.smtp_username
                smtp_password = sender.smtp_password
                use_tls = sender.use_tls
                spine_soft_template_user = html.escape(sender.spine_soft_template_user,quote=True)
                spine_soft_subject_user = sender.spine_soft_subject_user
                spine_medium_template_user = html.escape(sender.spine_medium_template_user,quote=True)
                spine_medium_subject_user = sender.spine_medium_subject_user
                spine_firm_template_user = html.escape(sender.spine_firm_template_user,quote=True)
                spine_firm_subject_user = sender.spine_firm_subject_user
                spine_xfirm_template_user = html.escape(sender.spine_xfirm_template_user,quote=True) 
                spine_xfirm_subject_user = sender.spine_xfirm_subject_user
                spine_soft_template_admin = html.escape(sender.spine_soft_template_admin,quote=True)
                spine_soft_subject_admin = sender.spine_soft_subject_admin
                spine_medium_template_admin = html.escape(sender.spine_medium_template_admin,quote=True)
                spine_medium_subject_admin = sender.spine_medium_subject_admin
                spine_firm_template_admin = html.escape(sender.spine_firm_template_admin,quote=True)
                spine_firm_subject_admin = sender.spine_firm_subject_admin
                spine_xfirm_template_admin = html.escape(sender.spine_xfirm_template_admin,quote=True)
                spine_xfirm_subject_admin = sender.spine_xfirm_subject_admin
        else:
            smtp_host = settings.EMAIL_HOST
            smtp_port = settings.EMAIL_PORT
            smtp_username = settings.EMAIL_HOST_USER
            smtp_password = settings.EMAIL_HOST_PASSWORD
            use_tls = settings.EMAIL_USE_TLS
            
    return JsonResponse({"shop":check_shop[0].shop, "smtp_host":smtp_host, "smtp_port":smtp_port, "smtp_username":smtp_username, "smtp_password":smtp_password, "use_tls":use_tls,"spine_soft_template_user" :spine_soft_template_user,"spine_soft_subject_user":spine_soft_subject_user,"spine_medium_template_user":spine_medium_template_user,"spine_medium_subject_user":spine_medium_subject_user,"spine_firm_template_user":spine_firm_template_user,"spine_firm_subject_user":spine_firm_subject_user,"spine_xfirm_template_user":spine_xfirm_template_user,"spine_xfirm_subject_user":spine_xfirm_subject_user,"spine_soft_template_admin":spine_soft_template_admin,"spine_soft_subject_admin":spine_soft_subject_admin,"spine_medium_template_admin":spine_medium_template_admin,"spine_medium_subject_admin":spine_medium_subject_admin,"spine_firm_template_admin":spine_firm_template_admin,"spine_firm_subject_admin":spine_firm_subject_admin,"spine_xfirm_template_admin":spine_xfirm_template_admin,"spine_xfirm_subject_admin":spine_xfirm_subject_admin})