import razorpay
import stripe
from django.contrib.auth import get_user_model
from django.db.models import Q
from django.shortcuts import render
from rest_framework.response import Response
# from harkat.models import HarkatClubDatabase
from lpp.models import MNFLPPDDatabase
# from institutional.models import *

# from institutional.views import get_discount
# from institutional.views import get_discount, make_transaction
from MNF import settings
from payment.models import privilegedUser1
# from mnfapp.models import (Author, MNFScriptDatabase, Notifications,
#                            PaymentData, PitchVector, SampleScript,
#                            centralDatabase)
# from conversion.models import (BookConversion, StoryConversion, UploadScript,
#                      pptconversion)
# from MNF.settings import (RUNNING_DISCOUNT_SUBTITLE,SUBTITLE_LPP,SUBTITLE_PER_SEC,GetMongoDBUrl,discount_limit_handler,CONVERSION_PER_PAGE, COUNTRY_KEY, EMAIL_HOST_USER,
#                           EMPLOY_DISCOUNT, LIFE_MEMBER_ADDITIONAL,
#                           LPP_PER_PAGE, RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET,
#                           RAZORPAY_PLATFORM_FEE, RUNNING_DISCOUNT_CONVERSION,
#                           STRIPE_PLATFORM_FEE, STRIPE_PUBLISHABLE_KEY,
#                           STRIPE_SECRET_KEY, T_RAZORPAY_KEY_ID,
#                           T_RAZORPAY_KEY_SECRET, YEARLY_MEMBER_ADDITIONAL,
#                           BasePath)
from MNF.settings import discount_limit_handler
from .models import *
from .serializers import *
# from pymongo import MongoClient
# from datetime import datetime, timedelta
# import pytz
# import pandas as pd
# from relationshipmanager.models import RMDatabase

# MongoDBUrl = GetMongoDBUrl()
# client = MongoClient(MongoDBUrl)
# db = client["DB"]
# User = get_user_model()
DISCOUNT = settings.DISCOUNT
import json
import requests
basePath = settings.BasePath()
from mnfapp.models import centralDatabase

# def excelLoader(path:str):
#     file_path = path
#     df = pd.read_excel(file_path)
#     return df

# def fetchMembership(df):
#     memberdict = {}
#     memberdict[df['Unnamed: 0'][2]] = df['Unnamed: 1'][2]
#     memberdict[df['Unnamed: 0'][3]] = df['Unnamed: 1'][3]
#     memberdict[df['Unnamed: 0'][4]] = df['Unnamed: 1'][4]
#     return memberdict

# def is_valid_time():
#     ist = pytz.timezone('Asia/Kolkata')
#     current_time = datetime.now(ist).time()
#     start_time = datetime.strptime('19:30:00', '%H:%M:%S').time()
#     end_time = datetime.strptime('21:30:00', '%H:%M:%S').time()
#     return start_time <= current_time <= end_time

# def apply_discount(original_price):
#     if is_valid_time():
#         return 47.5
#     else:
#         return original_price

def razorkey(request):
    RAZOR_KEY = settings.RAZORPAY_KEY_ID
    RAZOR_SECRET = settings.RAZORPAY_KEY_SECRET

    if request.user.is_superuser:
        RAZOR_KEY = settings.T_RAZORPAY_KEY_ID
        RAZOR_SECRET = settings.T_RAZORPAY_KEY_SECRET
    return RAZOR_KEY,RAZOR_SECRET

def stripeKey(request):
    api_key = settings.STRIPE_SECRET_KEY
    pub_key = settings.STRIPE_PUBLISHABLE_KEY
    if request.user.is_superuser:
        api_key = settings.T_STRIPE_SECRET_KEY
        pub_key = settings.T_STRIPE_PUBLISHABLE_KEY
    
    return api_key, pub_key

# def centralPayment_get_discounts11(request,amount,combo_discount=None,combo_discount_calculate=None, service=None):
#     pricelist = {}
#     data_user = centralDatabase.objects.get(user_id=request.user)
#     if data_user.contact != " ":
#        pricelist["contact"] = data_user.contact
#     else:
#        pricelist["contact"] = " "

#     if data_user.address != " ":
#        pricelist["address"] = data_user.address
#     else:
#        pricelist["address"] = " "

#     # Get today's date
#     # today = datetime.date.today()
#     # pricelist["date"] = today

#     # if data_user.city != " " or data_user.state != " " or data_user.country != " ":
#     #    pricelist["address"] = data_user.city + data_user.state + data_user.country
#     # else:
#     #     pricelist["address"] = " "
#     total_amount = amount
   
#     if combo_discount == None:
#        combo_discount = 0
#        combo_discount_calculate = 0
#     else:
#        combo_discount = combo_discount
#        combo_discount_calculate = combo_discount_calculate
#     pricelist["early_bird"] = discount_limit_handler(DISCOUNT["early_bird"])
#     pricelist["early_bird_calculate"] = round(float((total_amount-combo_discount_calculate)*pricelist["early_bird"]/100),2)
    
        
#     user = User.objects.get(id=request.user.id)
    
#     #staff discount
#     # rm = RMDatabase.objects.get(user_id=request.user.id)
#     # if rm.is_accepted:
#     #     pass
#     from harkat.models import HarkatClubDatabase
#     from lpp.models import MNFLPPDDatabase
#     if RMDatabase.objects.filter(id=request.user.id,is_accepted = True).exists() or MNFLPPDDatabase.objects.filter(user_id=request.user.id).exists() or HarkatClubDatabase.objects.filter(user_id=request.user.id).exists() or User.objects.get(id=request.user.id).is_staff :
#         pricelist["sdiscount"] = discount_limit_handler(DISCOUNT["employ_discount"])
#         pricelist["staff_discount_calculate"] = round(float((total_amount-combo_discount_calculate-pricelist["early_bird_calculate"])*pricelist["sdiscount"]/100),2)
#     else:
#         pricelist["sdiscount"] = 0
#         pricelist["staff_discount_calculate"] = 0
    

    
#     # if User.objects.get(id=request.user.id).is_staff:  # changes done by manoj
        
#     #     pricelist["sdiscount"] = discount_limit_handler(DISCOUNT["employ_discount"])
#     #     pricelist["staff_discount_calculate"] = round(float((total_amount-combo_discount_calculate-pricelist["early_bird_calculate"])*pricelist["sdiscount"]/100),2)
#     # else:
#     #     pricelist["sdiscount"] = 0
#     #     pricelist["staff_discount_calculate"] = 0

#     # manoj updated code for priviledged user
    
#     try:
#         memberType = privilegedUser1.objects.filter(user=user, is_active="yes") # changes done by manoj
#         if memberType:
#             memberType = memberType.first().memberType
#             pricelist["membershipNarration"] = 0
#             if memberType == "normal":
#                 pricelist["pdiscount"] = 0
#                 pricelist["membership_discount_calculate"] = 0
                
#             elif memberType == "yearly":
#                 pricelist["pdiscount"] = discount_limit_handler(DISCOUNT["yearly_member_additional"])
#                 pricelist["membership_discount_calculate"] = round(float((total_amount-combo_discount_calculate-pricelist["early_bird_calculate"]-pricelist["staff_discount_calculate"])*pricelist["pdiscount"]/100),2)
                
#             elif memberType == "Life Member":
#                 pricelist["pdiscount"] = discount_limit_handler(DISCOUNT["life_member_additional"])
#                 pricelist["membership_discount_calculate"] = round(float((total_amount-combo_discount_calculate-pricelist["early_bird_calculate"]-pricelist["staff_discount_calculate"])*pricelist["pdiscount"]/100),2)
#         if not privilegedUser1.objects.filter(user=request.user,is_active="yes").exists(): 
#             pricelist["membershipNarration"] = 1
#             pricelist["pdiscount"] = 0
#             pricelist["membership_discount_calculate"] = 0
#     except:
#         pricelist["pdiscount"] = 0
#         pricelist["membership_discount_calculate"] = 0

    
#     # Student discount
#     from institutional.views import get_discount
#     get_student_discount = get_discount(request.user.id,total_amount)
#     if get_student_discount == 0:
#         pricelist["student_discount"] = 0
#         pricelist["student_discount_calculate"] = 0
#     else:
#         pricelist["student_discount"] = get_student_discount
#         pricelist["student_discount_calculate"] = round(float((total_amount-combo_discount_calculate-pricelist["early_bird_calculate"]-pricelist["staff_discount_calculate"]-pricelist["membership_discount_calculate"])*pricelist["student_discount"]/100),2)
        
    
    
#     pricelist["total_discount"] = round(float(combo_discount_calculate + pricelist["early_bird_calculate"] + pricelist["staff_discount_calculate"] + pricelist["membership_discount_calculate"] + pricelist["student_discount_calculate"]),2)
#     pricelist["net_service_charge"] = round(float(total_amount - pricelist["total_discount"]),2)
#     pricelist["total_payable"] = round(float(pricelist["net_service_charge"]+pricelist["membershipNarration"]),2)
#     # GST 
#     pricelist["gst"] = discount_limit_handler(DISCOUNT["gst"])
#     pricelist["gst_calculate"] = round(float(pricelist["total_payable"]*pricelist["gst"]/100),2)
#     pricelist["gross_payable"] = round(float(pricelist["total_payable"] + pricelist["gst_calculate"] + pricelist["services_used"]),2)

#     return pricelist


# ########################################################################################################################
# def centralPayment(request, services:dict, redirectOnSucess:str, redirectOnFailed:str):
    
#     if services.keys == "narration":
#         totalAmount = narrationHandler(request, services["script_id"])
#         finalAmount = discountHandler(totalAmount)
#         indent_context = create_indent(request,"Pitchdeck",script_id,len(service_use), "",pricelist["total_amount"], context["net_payable"],pricelist["Total_discount"])
#         sucess = invoiceGenrator(totalAmount, indent_context, invoiceGenrator, redirectOnSucess, redirectOnFailed)
#         _ = afterInvoiceHandler(request)
#         if sucess:
#             create_indent()
#             callback()
#         else:
#             return "Error"


#     elif services.keys == "projectCenter":
#         totalAmount = projectCenterHandler(request, services["script_id"])
#         finalAmount = projectcenterdiscountHandler(totalAmount)
#         context = create_indent(request,'projectcenter',sr.data["projectid"],1,'',amount,sr.data["charges"],sr.data["discount"])

#         sucess = invoiceGenrator(totalAmount, invoiceGenrator,redirectOnSucess,redirectOnFailed)
#         if sucess:
#             create_indent()
#             callback()
#         else:
#             return "Error"

#     elif services.keys == "massiha":
#         totalAmount == massihaHandler()
#         inalAmount = discountHandler(totalAmount)
#         sucess = invoiceGenrator(totalAmount, invoiceGenrator,redirectOnSucess,redirectOnFailed)
#         if sucess:
#             create_indent()
#             callback()
#         else:
#             return "Error"

#     else:
#         assert "services Name Invalid"
    
    
# def narrationHandler(request, script_id="scr_1691823380"):
#     script_info = MNFScriptDatabase.objects.get(script_id=script_id)
#     vector_info = PitchVector.objects.get(script_id=script_id)
#     numPages = script_info.numPages
#     amt_linebyline = 0
#     amt_character_intro = 0
#     amt_screenplay_analysis = 0
#     amt_elevator_pitch = 0
#     amt_onepager = 0
#     amt_characterwise_narration = 0

#     if script_info.linebyline == "True":
#         amt_linebyline = settings.LINE_BY_LINE * numPages

#     if script_info.onepager == "True":
#         if numPages > 0 and numPages <= 15:
#             amt_onepager = settings.ONE_PAGER1
#         if numPages >= 16 and numPages <= 50:
#             amt_onepager = settings.ONE_PAGER2
#         if numPages >= 51 and numPages <= 100:
#             amt_onepager = settings.ONE_PAGER3
#         if numPages > 100:
#             amt_onepager = settings.ONE_PAGER4

#     if script_info.elevator_pitch == "True":
#         if numPages > 0 and numPages <= 15:
#             amt_elevator_pitch = settings.ELEVATOR_PITCH1
#         if numPages >= 16 and numPages <= 50:
#             amt_elevator_pitch = settings.ELEVATOR_PITCH2
#         if numPages >= 51 and numPages <= 100:
#             amt_elevator_pitch = settings.ELEVATOR_PITCH3
#         if numPages > 100:
#             amt_elevator_pitch = settings.ELEVATOR_PITCH4

#     if script_info.screenplay_analysis == "True":
#         if numPages > 0 and numPages <= 15:
#             amt_screenplay_analysis = settings.SCREENPLAY_ANALYSIS1
#         if numPages >= 16 and numPages <= 50:
#             amt_screenplay_analysis = settings.SCREENPLAY_ANALYSIS2
#         if numPages >= 51 and numPages <= 100:
#             amt_screenplay_analysis = settings.SCREENPLAY_ANALYSIS3
#         if numPages > 100:
#             amt_screenplay_analysis = settings.SCREENPLAY_ANALYSIS4

#     if script_info.character_intro == "True":
#         if numPages > 0 and numPages <= 15:
#             amt_character_intro = settings.CHARACTER_INTRODUCTION1
#         if numPages >= 16 and numPages <= 50:
#             amt_character_intro = settings.CHARACTER_INTRODUCTION2
#         if numPages >= 51 and numPages <= 100:
#             amt_character_intro = settings.CHARACTER_INTRODUCTION3
#         if numPages > 100:
#             amt_character_intro = settings.CHARACTER_INTRODUCTION4

#     if script_info.characterwise_narration == "True":
#         amt_characterwise_narration = settings.CHARACTERWISE_NARATION * numPages

#     total_amount = (
#         amt_linebyline
#         + amt_onepager
#         + amt_elevator_pitch
#         + amt_screenplay_analysis
#         + amt_character_intro
#         + amt_characterwise_narration
#     )
#     amount_charged = total_amount
    
#     amount_list = {}
#     if amt_linebyline > 0:
#         amount_list["amt_linebyline"] = amt_linebyline
        
#     if amt_onepager > 0:
#         amount_list["amt_onepager"] = amt_onepager
        
#     if amt_elevator_pitch > 0:
#         amount_list["amt_elevator_pitch"] = amt_elevator_pitch
        
#     if amt_screenplay_analysis > 0:
#         amount_list["amt_screenplay_analysis"] = amt_screenplay_analysis
        
#     if amt_character_intro > 0:
#         amount_list["amt_character_intro"] = amt_character_intro
        
#     if amt_characterwise_narration > 0:
#         amount_list["amt_characterwise_narration"] = amt_characterwise_narration
        
#     data = {
#             "total_amount": total_amount,
#             "amount_list": amount_list
#             }
    
#     return data

# #---------------------------------------------------project center payment---------------------------------------------------
# def projectCenterHandler(script_id):
#     script_info = MNFScriptDatabase.objects.get(script_id=script_id)
#     numPages = script_info.numPages
    
#     if numPages <= 10:
#         net_payment = 10
#         return net_payment

#     else:
#         net_payment = numPages 
#         return net_payment
    

# def projectcenterdiscountHandler(request,script_id):
#     paymentdata={}
#     paymentdata["net_payment"] = projectCenterHandler(script_id)
#     paymentdata["early_bird"] = discount_limit_handler(DISCOUNT["early_bird"])
#     paymentdata["early_bird_calculate"] = round(float( paymentdata["net_payment"] * paymentdata["early_bird"] / 100),2)
    
#     #staff discount 30%
#     if User.objects.get(id=request.user.id).is_staff:  # changes done by manoj
#         paymentdata["staff_discount"] = discount_limit_handler(DISCOUNT["employ_discount"])
#         paymentdata["staff_discount_calculate"] = round(float((paymentdata["net_payment"]-paymentdata["early_bird_calculate"])*paymentdata["staff_discount"]/100),2)
        
#     else:
#         paymentdata["staff_discount"] = 0
#         paymentdata["staff_discount_calculate"] = 0
       
#     # membership discount 
#     paymentdata["membership_discount"] = 0    
#     paymentdata["membership_discount_calculate"] = 0

#     memberType = privilegedUser1.objects.filter(user=request.user, is_active="yes") # changes done by manoj
#     if memberType:
#         memberType = memberType.first().memberType
#         paymentdata["membership_amount"] = 0

#         if memberType == "normal":
#             paymentdata["membership_discount"] = 0
#             paymentdata["membership_discount_calculate"] = 0

            
#         elif memberType == "yearly":
#             paymentdata["membership_discount"] = discount_limit_handler(DISCOUNT["yearly_member_additional"])
#             paymentdata["membership_discount_calculate"] = round(float((paymentdata["net_payment"]-paymentdata["early_bird_calculate"]-paymentdata["staff_discount_calculate"])*paymentdata["membership_discount"]/100),2)
            
#         elif memberType == "Life Member":
#             paymentdata["membership_discount"] = discount_limit_handler(DISCOUNT["life_member_additional"])
#             paymentdata["membership_discount_calculate"] = round(float((paymentdata["net_payment"]-paymentdata["early_bird_calculate"]-paymentdata["staff_discount_calculate"])*paymentdata["membership_discount"]/100),2)
           
#     if not privilegedUser1.objects.filter(user=request.user,is_active="yes").exists():   
#         paymentdata["membership_amount"] = 1
#         paymentdata["membership_discount"] = 0
#         paymentdata["membership_discount_calculate"] = 0
        

#     from institutional.views import get_discount
#     # Student discount
#     get_student_discount = get_discount(request.user.id)
#     if get_student_discount == 0:
#         paymentdata["student_discount"] = 0
#         paymentdata["student_discount_calculate"] = 0
        
#     else:
#         paymentdata["student_discount"] = get_student_discount
#         paymentdata["student_discount_calculate"] = float((paymentdata["net_payment"]-paymentdata["early_bird_calculate"]-paymentdata["staff_discount_calculate"]-paymentdata["membership_discount_calculate"])*paymentdata["student_discount"]/100)
    
#     # paymentdata["Total_discount"] = paymentdata["early_bird"] + paymentdata["staff_discount"] + paymentdata["membership_discount"] + paymentdata["student_discount"]

#     paymentdata["Total_discount"] = round(float(paymentdata["early_bird_calculate"] + paymentdata["staff_discount_calculate"] + paymentdata["membership_discount_calculate"] + paymentdata["student_discount_calculate"]),2)
#     paymentdata["remaining_amount"] =round(float(paymentdata["net_payment"]- paymentdata["Total_discount"]),2)
#     # GST 
#     paymentdata["GST"] = settings.GST
#     paymentdata["GST_calculate"] = round(float(paymentdata["remaining_amount"]*paymentdata["GST"]/100),2)
#     paymentdata["Total_amount"] = round(float(paymentdata["remaining_amount"] + paymentdata["GST_calculate"]+paymentdata["membership_amount"]),2)
    

#     return paymentdata

# from django.shortcuts import HttpResponse, render


# def projectCenterScriptDetail(request,projectid,script_id):
#     y = MNFScriptDatabase.objects.get(script_id=script_id)
    
#     gmodel = db["projectcenter_generatedmodel"]
#     gdata=gmodel.find_one({"projectid":projectid})
#     # gdata=Generatedmodel.objects.get(scriptid=script_id)
#     paymentdata={
#         "owner":gdata['owner'],
#         "script":gdata['project_name'],
#         "page_no":y.numPages,
#         "budget":gdata['budget'],
#         "date":gdata['date'],
#         # "email":udata['user_email'],
        
#     }
    
    
#     return paymentdata

# def invoiceGenratorproject(request,script_id="scr_1695826846",projectid="31601"):
#     context = {}
#     context["temp"] = projectCenterHandler(script_id=script_id)
#     # context.update({"amount_list":temp.get("amount_list",{})})
#     # context.update({"total_amount":temp["total_amount"]})
#     context["user_discount_data"] = projectcenterdiscountHandler(request,script_id)
#     # context.update({"discount":user_discount_data["total_discount"]})
#     # context.update(user_discount_data.get("discount_list",{}))
#     # context.update(user_discount_data.get("discount_amount",{}))
#     context["script_details"] = projectCenterScriptDetail(request,projectid=projectid,script_id=script_id)
#     # context.update(script_details)
#     data_json = json.dumps(context)
    
#     return HttpResponse(data_json, content_type="application/json")

#     # return context
#     # return render(request, "Pitchdeck/narration_checkoutnew.html", context)


# #------------------------------------------------------end-----------------------------------------------------------

# #--------------------------------------subtitiling payment-----------------------------------------------------------
# from subtitling3.models import Subtitles

# def subtitleHandler(s_id):
#     script = Subtitles.objects.get(s_id=s_id)
#     service_charges = settings.SUBTITLE_PER_SEC
#     duration=script.video_duration
#     service_lpp = settings.SUBTITLE_LPP
#     pass
# def subtitlediscountHandler():
#     pass
# def subtitleScriptDetail():
#     pass
# def invoiceGenratorSubtitle():
#     pass



# def conversionHandler():
#     pass
# from conversion.models import pptconversion
# def conversionpptHandler(ppt_string="1672222204.0831811-ppt"):
#     ppt_data = pptconversion.objects.get(ppt_string=ppt_string)
#     with open("/home/user/mnf/project/MNF/projectcenter/error_check.txt","a") as file01:
#            file01.write("f: " + str(ppt_data) + "\n")

#     context={}
#     if ppt_data.lpp == True:
#         amt = ppt_data.slide_count * CONVERSION_PER_PAGE
#         context["total"] = round(amt, 2)

#         lppamt = (ppt_data.slide_count * CONVERSION_PER_PAGE) + (
#             ppt_data.slide_count * LPP_PER_PAGE
#         )
#         context["onlylppfee"] = round((ppt_data.slide_count * LPP_PER_PAGE), 2)
#         # amount_to_be_given_to_lpp = round(
#         #     mdiscount * context["onlylppfee"] * pdiscount * sdiscount, 2
#         # )
#         context["subtotal"] = round(lppamt, 2)
        
#     else:
        
#         amt = ppt_data.slide_count * CONVERSION_PER_PAGE
#         context["total"] = round(amt, 2)
#         context["subtotal"] = round(amt, 2)

#     data_json = json.dumps(context)
    
#     return HttpResponse(data_json, content_type="application/json")


# def massihaHandler():
#     pass

# def discountHandler(request):
#     total_discount = 0
#     discount_list = {}
#     user = request.user
    
#     # Staff discount
#     if user.is_staff:
#         staff_discount = discount_limit_handler(DISCOUNT["employ_discount"])
#     else:
#         staff_discount = 0
    
#     # Previleged user discount
#     try:
#         memberType = privilegedUser1.objects.filter(user=user, is_active="yes")
#         if memberType:
#             memberType = memberType.first().memberType
#             if memberType == "normal":
#                 pu_discount = 0
                
#             elif memberType == "yearly":
#                 pu_discount = discount_limit_handler(DISCOUNT["yearly_member_additional"])
                
#             elif memberType == "Life Member":
#                 pu_discount = discount_limit_handler(DISCOUNT["life_member_additional"])
                
        
#         if not privilegedUser1.objects.filter(user=request.user, is_active="yes").exists():
#             pu_discount = 0
    
#     except:
#         pu_discount = 0
        
#     # Student discount
#     from institutional.views import get_discount
#     get_student_discount = get_discount(request.user.id)
    
#     if get_student_discount == 0:
#         student_discount = 0
    
#     else:
#         student_discount = get_student_discount
        
#     total_discount = (staff_discount + pu_discount + student_discount)
    
#     if staff_discount > 0:
#         discount_list["staff_discount"] = staff_discount
        
#     if pu_discount > 0:
#         discount_list["pu_discount"] = pu_discount
        
#     if student_discount > 0:
#         discount_list["student_discount"] = student_discount 
       
#     data = {
#             "total_discount": total_discount,
#             "discount_list": discount_list
#             }
#     data_json = json.dumps(data)
    
#     return HttpResponse(data_json, content_type="application/json")

# def invoiceGenrator(request,context):
#     return render(request, "Pitchdeck/narration_checkoutnew.html", context)



#########################################################################################################






def get_user_location(request):
    try:
        ip_address = request.META.get('HTTP_X_FORWARDED_FOR') or request.META.get('REMOTE_ADDR')
        url = f"https://ipinfo.io/{ip_address}/json"
        response = requests.get(url)
        data = response.json()
        return data['country']
    except:
        location = "others"
        return location
    
def create_indent(request,services_used,services_id,qtn,promo_code,total_amount,amount_charged,discount):
    context = {}
    if not request and services_used and services_id and qtn and total_amount and amount_charged and discount:
        context['error'] = 'invalied request'
        return context
    
    location = get_user_location(request)   
    user = User.objects.get(id=request.user.id)

    # from institutional.views import get_discount
    # get_student_discount = get_discount(request.user.id,total_amount)
    # if get_student_discount == 0:
    #     pass
    # else:
    #     amount_charged = round(float((amount_charged*get_student_discount/100),2)

    # monthly_user = make_transaction(request.user.id, services_used, services_id,amount_charged)
    monthly_user = False
    if monthly_user:        
        pay_instance = CentralPayment()
        pay_instance.promo_code = promo_code
        pay_instance.services_used = services_used
        pay_instance.services_id = services_id
        pay_instance.user_id = user
        pay_instance.qtn = qtn
        pay_instance.total_amount = total_amount
        pay_instance.amount_charged = amount_charged
        pay_instance.discount = discount
        # pay_instance.im_discount = im_discount
        pay_instance.payment_status = "monthly_user"
        pay_instance.save()
        context['monthly_user'] = 'bill added to the transaction account'
        context['central_pay_id'] = str(pay_instance.id) 
        return context
    
    
    
    # member_type =  privilegedUser1.objects.filter(user=request.user).exists()
    # if not member_type:
    #     amount_charged += 1
    #     total_amount += 1
    
    # with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
    #         curr = json.load(c)
    #         try:
    #             rate = curr["rates"]["INR"]
    #         except Exception as e:
    #             rate = 80
                
    # Gateway charge
    rate = 80
    amount_charged += 0.03  

    if location == "IN":         
        amount = amount_charged * rate
        RAZOR_KEY,RAZOR_SECRET  = razorkey(request)
        razorpay_client = razorpay.Client(auth=(RAZOR_KEY, RAZOR_SECRET))
        razorpay_order = razorpay_client.order.create(
            {
                "amount": int(amount) * 100,
                "currency": "INR",
                "payment_capture": "1",
            }
        )
        pay_instance = CentralPayment()
        pay_instance.promo_code = promo_code
        pay_instance.services_used = services_used
        pay_instance.services_id = services_id
        pay_instance.user_id = user
        pay_instance.qtn = qtn
        pay_instance.total_amount = total_amount
        pay_instance.amount_charged = amount_charged
        pay_instance.discount = discount
        # pay_instance.im_discount = im_discount
        pay_instance.gateway_fee = 0.03
        pay_instance.currency = "INR"
        pay_instance.payment_gateway = "razorPay"
        pay_instance.payment_status = "init"
        pay_instance.order_id = razorpay_order["id"]
        pay_instance.save()

        context['orderId'] = pay_instance.order_id
        context['currency'] = pay_instance.currency
        context['amount'] = pay_instance.amount_charged
        context['merchantId'] = RAZOR_KEY    
        context['central_pay_id'] = str(pay_instance.id)  
    else:
        api_key, pub_key = stripeKey(request)
        stripe.api_key = api_key
        amount = amount_charged * rate
        customer = stripe.Customer.create(email=request.user.email,)
        intent = stripe.PaymentIntent.create(
                description="MNF Software services",
                amount=int(amount * 100),
                currency='INR',
                automatic_payment_methods={'enabled': True},
                customer=customer.id,
            )     
        pay_instance = CentralPayment()
        pay_instance.promo_code = promo_code
        pay_instance.services_used = services_used
        pay_instance.services_id = services_id
        pay_instance.user_id = user
        pay_instance.qtn = qtn
        pay_instance.total_amount = total_amount
        pay_instance.amount_charged = amount_charged
        pay_instance.discount = discount
        pay_instance.gateway_fee = 0.03
        pay_instance.currency = 'USD'
        pay_instance.payment_gateway = "Stripe"
        pay_instance.payment_status = "init"
        pay_instance.order_id = intent.client_secret
        pay_instance.save()

        context['client_secret'] = pay_instance.order_id
        context['currency'] = pay_instance.currency
        context['amount'] = pay_instance.amount_charged
        context['central_pay_id'] = str(pay_instance.id)
        context['pub_key'] = pub_key

    return context    
    
def callback(response, request):
    context = {}
    
    if "razorpay_signature" in response:
        print("respoonse")
        RAZOR_KEY,RAZOR_SECRET  = razorkey(request)
        razorpay_client = razorpay.Client(auth=(RAZOR_KEY, RAZOR_SECRET))
        verify = razorpay_client.utility.verify_payment_signature(response)
        payDetail = razorpay_client.payment.fetch(response["razorpay_payment_id"])
        pay_instance = CentralPayment.objects.get(order_id=response["razorpay_order_id"])

        if verify:
            print("verify")    
            pay_instance.payment_id = response["razorpay_payment_id"]
            pay_instance.signature_id = response["razorpay_signature"]
            pay_instance.payment_status = "success"
            pay_instance.save()

            member_type =  privilegedUser1.objects.filter(user=request.user).exists()
            if not member_type:
                user = User.objects.get(id=request.user.id)
                lasto = privilegedUser1.objects.order_by('-id').first()
                subcription = privilegedUser1()
                # last_entry = Testmodel.objects.order_by('-id').first()
                subcription.id = int(lasto.id) + 1
                subcription.user = user
                subcription.is_active = "yes"
                subcription.memberType = "normal"
                subcription.months = 1
                subcription.save()
            context['payment_status'] = "success"
            context['central_pay_id'] = str(pay_instance.id)
            context['payment_id'] = pay_instance.payment_id
        else:
            pay_instance.payment_status = "failed"
            pay_instance.save()

            context['payment_status'] = "failed"
            context['central_pay_id'] = str(pay_instance.id)   

    elif "client_secret" in response :        
        pay_instance = CentralPayment.objects.get(order_id=response["client_secret"])
        if response["status"]=="succeeded":
            pay_instance.payment_id = response["id"]
            pay_instance.signature_id = ""
            pay_instance.payment_status = "success"
            pay_instance.save()
            member_type =  privilegedUser1.objects.filter(user=request.user).exists()
            if not member_type:
                user = User.objects.get(id=request.user.id)
                lasto = privilegedUser1.objects.order_by('-id').first()
                subcription = privilegedUser1()
                # last_entry = Testmodel.objects.order_by('-id').first()
                subcription.id = int(lasto.id) + 1
                subcription.user = user
                subcription.is_active = "yes"
                subcription.memberType = "normal"
                subcription.months = 1
                subcription.save()
                
            context['payment_status'] = "success"
            context['central_pay_id'] = str(pay_instance.id)
            context['payment_id'] = pay_instance.payment_id

        else:
            pay_instance.payment_status = "failed"
            pay_instance.save()

            context['payment_status'] = "failed"
            context['central_pay_id'] = str(pay_instance.id) 
    else:
        context['payment_status'] = "failed"
    return context
    
def auto_refund(id, custom_amount=None):
    refund_object = CentralPayment.objects.get(id=id)
    if refund_object.payment_status == "refunded":
        return True

    try:
        gateway = refund_object.payment_gateway
        if gateway == "razorPay":
            RAZOR_KEY = settings.RAZORPAY_KEY_ID
            RAZOR_SECRET = settings.RAZORPAY_KEY_SECRET
            client = razorpay.Client(auth=(RAZOR_KEY, RAZOR_SECRET))
            amount = custom_amount if custom_amount else float(refund_object.amount_charged)
            amount_in_cents = str(int(amount * 100))
            refund = client.payment.refund(refund_object.payment_id, {'amount': amount_in_cents})
            if refund.get('status') == 'processed':
                refund_object.payment_status = "refunded"
                refund_object.save()
                return True
            else:
                refund_object.payment_status = "refunded-rejected"
                refund_object.save()
                return False
        elif gateway == "Stripe":
            amount = custom_amount if custom_amount else float(refund_object.amount_charged)
            amount_in_cents = str(int(amount * 100))
            refund = stripe.Refund.create(charge=refund_object.payment_id,amount=amount_in_cents)
            if refund.status == 'succeeded':
                refund_object.payment_status = "refunded"
                refund_object.save()
                return True
            else:
                refund_object.payment_status = "refunded-rejected"
                refund_object.save()
                return False
        else:
            return False
    except Exception as error:
        return False

    
def afterInvoiceHandler(request):
    pass


            
            

    

from rest_framework import status, viewsets
from rest_framework.exceptions import PermissionDenied
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.authentication import JWTAuthentication

from .models import *
from .serializers import *
from rest_framework.decorators import (api_view, authentication_classes,
                                       permission_classes)

class CPAPIPagination(PageNumberPagination):
    page_size = 15
    page_size_query_param = 'page_size'


# API to filter all data based on user

class CPUserViewSet(viewsets.ModelViewSet):
    queryset = CentralPayment.objects.all()
    serializer_class = CentralPaymentSerializer
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JWTAuthentication,)
    pagination_class = CPAPIPagination
   
    
    def get_queryset(self):
        user = self.request.user
        if user:
            print("cp line288", user)
            
            queryset = CentralPayment.objects.filter(user_id=user)
        return queryset


class CPAdminViewSet(viewsets.ModelViewSet):
    queryset = CentralPayment.objects.all()
    serializer_class = CentralPaymentSerializer
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JWTAuthentication,)
    pagination_class = CPAPIPagination
       
    def get_queryset(self):
        user = self.request.user
        if not user.is_superuser:
            raise PermissionDenied("You are not authorized to access this data.")

        else:
            pay_status = self.request.query_params.get("payment_status")
            queryset = CentralPayment.objects.filter(payment_status="pay_status").order_by('-date')
        return CentralPayment.objects.all()
                     
        
# Admin Actions
class AdminAction(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JWTAuthentication,)

    def post(self, request):
        sr = AdminActionSerializer(data=request.data)
        if sr.is_valid(raise_exception=True):
            instance = CentralPayment.objects.get(id=sr.data['id'])
            action = sr.data['action']
            if action == 'accept':
                if request.user.is_superuser:
                    cp_status = auto_refund(sr.data['id'])
                    if cp_status:
                        instance.payment_status = "refunded"
                        instance.save()
                        return Response({"status": "refund accepted"}, status=status.HTTP_200_OK)
                    else:
                        instance.payment_status = "refund-claimed"
                        instance.save()
                        return Response({"status": "something went wrong!"}, status=status.HTTP_400_BAD_REQUEST)
                else:
                    return Response({"status": "invalid request!"}, status=status.HTTP_400_BAD_REQUEST)
            elif action =='reject':
                instance.payment_status = "refunded-rejected"
                instance.save()
                return Response({"status": "refund rejected"}, status=status.HTTP_200_OK)
            else:
                return Response({"status": "invalid request!"}, status=status.HTTP_400_BAD_REQUEST)


class ClimedRefund(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JWTAuthentication,)
    
    def get(self,request,pk):
        instance = CentralPayment.objects.get(id=pk)
        if instance.user_id.id == request.user.id:
            instance.payment_status = "refund-claimed"
            instance.save()
            return Response({"status": "climed successfully"}, status=status.HTTP_200_ok)
        else:
            return Response({"status": "invalid request!"}, status=status.HTTP_400_BAD_REQUEST)


        


# @api_view(["GET", "DELETE", "POST", "PUT", "PATCH"])
# # @authentication_classes([JWTAuthentication])
# # @permission_classes([IsAuthenticated])
# def juggernautapi(request,pk=None):
#     if request.method == "GET":
#         if pk is not None:
#             main = JuggernautPackage.objects.all().filter(user_id=pk)
#             serializer = JuggernautPackageSerializer(main, many=True)
#             return Response(serializer.data)
#         main = JuggernautPackage.objects.all()
#         serializer = JuggernautPackageSerializer(main, many=True)
#         return Response(serializer.data)
#     if request.method == "POST":
#         serializer = JuggernautPackageSerializer(data=request.data)
#         if serializer.is_valid():
#             serializer.save()
#             return Response("data created")
#         return Response(serializer.errors)
#     if request.method == "PUT":
#         main = JuggernautPackage.objects.get(id=pk)
#         serializer = JuggernautPackageSerializer(main, data=request.data)
#         if serializer.is_valid():
#             serializer.save()
#             return Response("complete data updated")
#         return Response(serializer.errors)
#     if request.method == "PATCH":
#         main = JuggernautPackage.objects.get(id=pk)
#         serializer = JuggernautPackageSerializer(main, data=request.data, partial=True)
#         if serializer.is_valid():
#             serializer.save()
#             return Response("partial data updated")
#         return Response(serializer.errors)
#     if request.method == "DELETE":
#         if id is not None:
#             main = JuggernautPackage.objects.filter(id=pk)
#         # else:
#         #     main = MemberProfile.objects.filter(projectid=pk)
#         main.delete()
#         return Response("data deleted")
    
# @api_view(["GET"])
# def juggernaut_project_center_api(request,pk=None):
#     if request.method == "GET":
#         if pk is not None:
#             main = JuggernautProjectCenter.objects.all().filter(package=pk)
#             serializer = JuggernautProjectCenterSerializer(main, many=True)
#             return Response(serializer.data)
#         main = JuggernautProjectCenter.objects.all()
#         serializer = JuggernautProjectCenterSerializer(main, many=True)
#         return Response(serializer.data)
    
# @api_view(["GET"])
# def juggernaut_narration_api(request,pk=None):
#     if request.method == "GET":
#         if pk is not None:
#             main = JuggernautNarration.objects.all().filter(project_name=pk)
#             serializer = JuggernautNarrationSerializer(main, many=True)
#             return Response(serializer.data)
#         main = JuggernautNarration.objects.all()
#         serializer = JuggernautNarrationSerializer(main, many=True)
#         return Response(serializer.data) 
    

# @api_view(["GET"])
# def juggernaut_pitchdeck_api(request,pk=None):
#     if request.method == "GET":
#         if pk is not None:
#             main = JuggernautPitchdeck.objects.all().filter(project_name=pk)
#             serializer = JuggernautPitchdeckSerializer(main, many=True)
#             return Response(serializer.data)
#         main = JuggernautPitchdeck.objects.all()
#         serializer = JuggernautPitchdeckSerializer(main, many=True)
#         return Response(serializer.data) 
    
# @api_view(["GET"])
# def juggernaut_conversion_api(request,pk=None):
#     if request.method == "GET":
#         if pk is not None:
#             main = JuggernautConversion.objects.all().filter(package=pk)
#             serializer = JuggernautConversionSerializer(main, many=True)
#             return Response(serializer.data)
#         main = JuggernautConversion.objects.all()
#         serializer = JuggernautConversionSerializer(main, many=True)
#         return Response(serializer.data) 
    
# @api_view(["GET"])
# def juggernaut_subtitle_api(request,pk=None):
#     if request.method == "GET":
#         if pk is not None:
#             main = JuggernautSubtitling.objects.all().filter(package=pk)
#             serializer = JuggernautSubtitleSerializer(main, many=True)
#             return Response(serializer.data)
#         main = JuggernautSubtitling.objects.all()
#         serializer = JuggernautSubtitleSerializer(main, many=True)
#         return Response(serializer.data) 
    
# @api_view(["GET"])
# def juggernaut_beatsheet_api(request,pk=None):
#     if request.method == "GET":
#         if pk is not None:
#             main = JuggernautBeatSheet.objects.all().filter(project_name=pk)
#             serializer = JuggernautBeatSheetSerializer(main, many=True)
#             return Response(serializer.data)
#         main = JuggernautBeatSheet.objects.all()
#         serializer = JuggernautBeatSheetSerializer(main, many=True)
#         return Response(serializer.data)
    
    
    
    
    
def centralPayment_get_discounts(request,amount,combo_discount=None,combo_discount_calculate=None, service=None):
    pricelist = {
        "sdiscount": 0,
        "staff_discount_calculate":0,
        "pdiscount":0,
        "membership_discount_calculate":0, 
        "student_discount_calculate":0,
        "student_discount":0,
        "membershipNarration":1,
        }
    
    data_user = centralDatabase.objects.get(user_id=request.user)
    if data_user.contact != " ":
       pricelist["contact"] = data_user.contact
    else:
       pricelist["contact"] = " "

    if data_user.address != " ":
       pricelist["address"] = data_user.address
    else:
       pricelist["address"] = " "

    total_amount = amount
    
    if combo_discount == None:
       combo_discount = 0
       combo_discount_calculate = 0
    else:
       combo_discount = combo_discount
       combo_discount_calculate = combo_discount_calculate
    # pricelist["early_bird"] = discount_limit_handler(DISCOUNT["early_bird"])
    pricelist["early_bird"] = 30
    
    pricelist["early_bird_calculate"] = round(float((total_amount-combo_discount_calculate)*pricelist["early_bird"]/100),2)
    
        
    user = User.objects.get(id=request.user.id)
    
    if RMDatabase.objects.filter(id=request.user.id,is_accepted = True).exists() or MNFLPPDDatabase.objects.filter(user_id=request.user.id).exists() or HarkatClubDatabase.objects.filter(user_id=request.user.id).exists() or User.objects.get(id=request.user.id).is_staff :
        #------------team discount
        if RMDatabase.objects.filter(id=request.user.id,is_accepted = True).exists() or MNFLPPDDatabase.objects.filter(user_id=request.user.id).exists() or HarkatClubDatabase.objects.filter(user_id=request.user.id).exists() or User.objects.get(id=request.user.id).is_staff :
            pricelist["sdiscount"] = discount_limit_handler(DISCOUNT["employ_discount"])
            pricelist["staff_discount_calculate"] = round(float((total_amount-combo_discount_calculate-pricelist["early_bird_calculate"])*pricelist["sdiscount"]/100),2)
        else:
            pricelist["sdiscount"] = 0
            pricelist["staff_discount_calculate"] = 0
        #---------membership discount
        memberType = privilegedUser1.objects.filter(user=user, is_active="yes") # changes done by manoj
        if memberType:
            memberType = memberType.first().memberType
            pricelist["early_birdteamembershipNarration"] = 0
            if memberType == "normal":
                pricelist["pdiscount"] = 0
                pricelist["membership_discount_calculate"] = 0
                
            elif memberType == "yearly":
                pricelist["pdiscount"] = discount_limit_handler(DISCOUNT["yearly_member_additional"])
                pricelist["membership_discount_calculate"] = round(float((total_amount-combo_discount_calculate-pricelist["early_bird_calculate"]-pricelist["staff_discount_calculate"])*pricelist["pdiscount"]/100),2)
                
            elif memberType == "Life Member":
                pricelist["pdiscount"] = discount_limit_handler(DISCOUNT["life_member_additional"])
                pricelist["membership_discount_calculate"] = round(float((total_amount-combo_discount_calculate-pricelist["early_bird_calculate"]-pricelist["staff_discount_calculate"])*pricelist["pdiscount"]/100),2)
        if not privilegedUser1.objects.filter(user=request.user,is_active="yes").exists(): 
            pricelist["membershipNarration"] = 1
            pricelist["pdiscount"] = 0
            pricelist["membership_discount_calculate"] = 0
            
    elif UnaffiliatedStudent.objects.filter(user=user).exists() or WaitForInstituteStudent.objects.filter(user=user).exists() or AffiliatedStudent.objects.filter(user=user).exists():
       
        #-------------Annual discount
        memberType = privilegedUser1.objects.filter(user=user, is_active="yes") # changes done by manoj
        if memberType:
            memberType = memberType.first().memberType
            
            if memberType == "yearly":
                pricelist["membershipNarration"] = 0
                pricelist["pdiscount"] = discount_limit_handler(DISCOUNT["yearly_member_additional"])
                pricelist["membership_discount_calculate"] = round(float((total_amount-combo_discount_calculate-pricelist["early_bird_calculate"]-pricelist["staff_discount_calculate"])*pricelist["pdiscount"]/100),2)
            else:
                pricelist["membershipNarration"] = 0   
                pricelist["pdiscount"] = 0
                pricelist["membership_discount_calculate"] = 0    
        if not privilegedUser1.objects.filter(user=request.user,is_active="yes").exists(): 
            pricelist["membershipNarration"] = 1 
            pricelist["pdiscount"] = 0
            pricelist["membership_discount_calculate"] = 0   
        
         #---------------student discount
        get_student_discount = get_discount(request.user.id,total_amount)
        if get_student_discount == 0:
            pricelist["student_discount"] = 0
            pricelist["student_discount_calculate"] = 0
        else:
            pricelist["student_discount"] = 50
            pricelist["student_discount_calculate"] = round(float((total_amount-combo_discount_calculate-pricelist["early_bird_calculate"]-pricelist["staff_discount_calculate"]-pricelist["membership_discount_calculate"])*pricelist["student_discount"]/100),2)
        
      
    elif privilegedUser1.objects.filter(user=user, is_active="yes").exists():
        memberType = privilegedUser1.objects.filter(user=user, is_active="yes") # changes done by manoj
        if memberType:
            memberType = memberType.first().memberType
            pricelist["membershipNarration"] = 0
            # if memberType == "normal":
            #     pricelist["pdiscount"] = 0
            #     pricelist["membership_discount_calculate"] = 0
                
            
            if memberType == "yearly":
                
                #------------team discount
                if RMDatabase.objects.filter(id=request.user.id,is_accepted = True).exists() or MNFLPPDDatabase.objects.filter(user_id=request.user.id).exists() or HarkatClubDatabase.objects.filter(user_id=request.user.id).exists() or User.objects.get(id=request.user.id).is_staff :
                    pricelist["sdiscount"] = discount_limit_handler(DISCOUNT["employ_discount"])
                    pricelist["staff_discount_calculate"] = round(float((total_amount-combo_discount_calculate-pricelist["early_bird_calculate"])*pricelist["sdiscount"]/100),2)
                else:
                    pricelist["sdiscount"] = 0
                    pricelist["staff_discount_calculate"] = 0
                #-----member discount
                pricelist["pdiscount"] = discount_limit_handler(DISCOUNT["yearly_member_additional"])
                pricelist["membership_discount_calculate"] = round(float((total_amount-combo_discount_calculate-pricelist["early_bird_calculate"]-pricelist["staff_discount_calculate"])*pricelist["pdiscount"]/100),2)
                #---------student discount
                if UnaffiliatedStudent.objects.filter(user=user).exists() or WaitForInstituteStudent.objects.filter(user=user).exists() or AffiliatedStudent.objects.filter(user=user).exists():
                
                    get_student_discount = get_discount(request.user.id,total_amount)
                    if get_student_discount == 0:
                        pricelist["student_discount"] = 0
                        pricelist["student_discount_calculate"] = 0
                    else:
                        pricelist["student_discount"] = 50
                        pricelist["student_discount_calculate"] = round(float((total_amount-combo_discount_calculate-pricelist["early_bird_calculate"]-pricelist["staff_discount_calculate"]-pricelist["membership_discount_calculate"])*pricelist["student_discount"]/100),2)
            
            if memberType == "Life Member":
                #------------stafff discount
                if RMDatabase.objects.filter(id=request.user.id,is_accepted = True).exists() or MNFLPPDDatabase.objects.filter(user_id=request.user.id).exists() or HarkatClubDatabase.objects.filter(user_id=request.user.id).exists() or User.objects.get(id=request.user.id).is_staff :
                    pricelist["sdiscount"] = discount_limit_handler(DISCOUNT["employ_discount"])
                    pricelist["staff_discount_calculate"] = round(float((total_amount-combo_discount_calculate-pricelist["early_bird_calculate"])*pricelist["sdiscount"]/100),2)
                else:
                    pricelist["sdiscount"] = 0
                    pricelist["staff_discount_calculate"] = 0
                pricelist["pdiscount"] = discount_limit_handler(DISCOUNT["life_member_additional"])
                pricelist["membership_discount_calculate"] = round(float((total_amount-combo_discount_calculate-pricelist["early_bird_calculate"]-pricelist["staff_discount_calculate"])*pricelist["pdiscount"]/100),2)
                
        
        if not privilegedUser1.objects.filter(user=request.user,is_active="yes").exists(): 
            pricelist["membershipNarration"] = 1 
            pricelist["pdiscount"] = 0
            pricelist["membership_discount_calculate"] = 0
            
    
    pricelist["total_discount"] = round(float(combo_discount_calculate + pricelist["early_bird_calculate"] + pricelist["staff_discount_calculate"] + pricelist["membership_discount_calculate"] + pricelist["student_discount_calculate"]),2)
    pricelist["net_service_charge"] = round(float(total_amount - pricelist["total_discount"]),2)
    pricelist["total_payable"] = round(float(pricelist["net_service_charge"]+pricelist["membershipNarration"]),2)
    # GST 
    pricelist["gst"] = discount_limit_handler(DISCOUNT["gst"])
    pricelist["gst_calculate"] = round(float(pricelist["total_payable"]*pricelist["gst"]/100),2)
    pricelist["gross_payable"] = round(float(pricelist["total_payable"] + pricelist["gst_calculate"]),2)

    return pricelist

class paymentTestView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        context = create_indent(request,'Subtitle','pk',1,'',10,10,0)     
        return Response(context, status=status.HTTP_200_OK)