from django.shortcuts import render, redirect,HttpResponse
from django.core.cache import cache
import json
import requests
from django.http import JsonResponse
import os
from django.views.decorators.csrf import csrf_exempt
from payupweb.settings import DEBUG
from payupweb.constants import CALLBACK_ACCES, HOST, KEY_TOKEN, TYPE_PAYMENT,WSHOST,DEBUG_HOST

# Create your views here.



def getToken():
    token = ""

    try:

        if cache.get(KEY_TOKEN) is not None:
            return cache.get(KEY_TOKEN)
        else:
            res = requests.post(HOST+"/api/v1/auth", data=json.dumps({"username": "paymentupgroup","password":"Dessdie43@"}))
            
            cache.set(KEY_TOKEN, "bearer "+res.json()["access_token"],3600)

            return cache.get(KEY_TOKEN)

    except Exception as e:
        print(e)

    return token



def is_ajax(request):
    return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'


def validParams(type:str,telephone:str,card_number:str, card_expire:str , card_cvv:str, otp:str):

    prefix = ["77","78","76","70","75"]
    
    if type !="CARD":
        
        if (telephone[:2] not in prefix or len(telephone.replace(" ","")) != 9 ) and type != "WAVE":
            print(telephone[:2],len(telephone.replace(" ","")),telephone)
            return False
    else:
        if len(card_number.replace(" ","")) != 16 or  "/" not in card_expire.replace(" ","") or len(card_cvv.replace(" ","")) != 3:
            
            return False

    if type not in TYPE_PAYMENT:
        print(type)
        return False

    return True



def payToUpWallet(request,my_slug_key):

    
    if is_ajax(request):
        print("starting.......")
        

        tel = request.POST.get('telephone', False)
        type = request.POST.get('type', False)
        slug = request.POST.get('slug', "")
        card_number = request.POST.get('card_number', False)
        card_expire = request.POST.get('card_expire', False)
        card_cvv = request.POST.get('card_cvv', False)
        
        fname = request.POST.get('fname', "")
        lname = request.POST.get('lname', "")
        
        omotp = request.POST.get('omotp', "")

        data = json.dumps({"status":"","message":""})
        print(tel,type,slug,my_slug_key)

        if tel != False and type != False and slug != False and validParams( str(type), str(tel),str(card_number), str(card_expire), str(card_cvv), str(omotp)  ):
            try:
                headers = {"slug":str(my_slug_key).replace(" ", ""),"Authorization":getToken(),"type":type,"tel":tel.replace(" ","")}
                
                data = {"cn":card_number,"ce":card_expire,"cc":card_cvv,"fn":fname,"ln":lname, "omotp":omotp}
                res = requests.post(HOST+"/api/v1/payment/pay",headers=headers, data= json.dumps(data))

                print(res.content)
                data = json.dumps(res.json())
                
            except Exception as e:
                print(e)
                data = json.dumps({"status":"ERROR","message":"erreur inconnu"})
        else:
            data = json.dumps({"status":"ERROR","message":"les informations fournies sont invalides"})
                
        print(data)
        mimetype = 'application/json'
        return HttpResponse(data, mimetype)
    
    mimetype = 'application/json'
    return HttpResponse(json.dumps("{'status':'ERROR'}"), mimetype)





METHODS_LIBELLE = {
    "OM":"Orange Money",
    "WAVE":"Wave"
}

def home(request,my_slug_key):
    context = {}
    
    print("keeeeeyyyyyy <<<<>>>>>>>>>>",my_slug_key)
    headers = {"slug":str(my_slug_key),"Authorization":getToken()}
    
    
    
    res = requests.get(HOST +"/api/v1/payment/getcheckout",headers=headers)
    
    print(res.json())
    myproducts=[]
    
    if res.json()["status"]=="SUCCES":

        context['data'] = res.json()["data"]
        total = 0.0
        devise ="XOF"

        products = res.json()["data"]["checkout"]["products"]
        image = res.json()["data"]["checkout"]["image"]
        methods = res.json()["data"]["checkout"]["methods"]
        methods = [[m,METHODS_LIBELLE[m]] for m in methods]
        

        products_obj = []
        
        company  = res.json()["data"]["company"]["company"]["name"] if res.json()["data"]["company"]["company"]["name"] !="" else "UPGROUP PAY"

        context["company"]=company
        
        for product in products:
            try:
                price=float(product[1][1])
                total+=price * product[3][1]
                products_obj.append(
                    {
                        "id": product[0][1],
                        "price": product[1][1],
                        "name": product[2][1],
                        "qte": product[3][1],
                    }
                )

            except Exception as e:
                print(e)


        context['products'] = products_obj
        context['methods'] = methods
        context['price'] = total
        context['devise'] = devise
        context['image'] = image if str(image).startswith("http") else ""
        context['slug'] = my_slug_key
        context['url'] = "{}/notify/{}/".format("ws://127.0.0.1:8080" if DEBUG else WSHOST, "checkout_"+res.json()["data"]["checkout"]['ref'])



    else:
        return redirect("/404")

    return render(request, "base.html", context)






@csrf_exempt
def om_callback(request):
    mimetype = 'application/json'
    print("-------------------- HEADERS  -----------------------------------")
    print(request.headers)
    print("-----------------------------------------------------------------")
    
    
    print("-------------------- BODY  ---------------------------------------")
    print(request.body)
    error = ""
    return HttpResponse(json.dumps({"result":"received"}), mimetype,status=200)
    try:
        if request.headers['Authorization'] == CALLBACK_ACCES:
            print("auth succes")
            
            headers = {"Authorization":getToken()}
            
            data = json.loads(request.body)
            res = requests.post(HOST+"/api/v1/payment/om/cb",headers=headers, data=json.dumps(data))
            
            return HttpResponse(json.dumps({"result":"received"}), mimetype,status=200)
        
    except Exception as e:
        print(e)
        
    
    
    return HttpResponse(json.dumps({"result":"access forbidden","e":error}), mimetype,status=403)



@csrf_exempt
def callback(request):
    mimetype = 'application/json'
    print("-------------------- HEADERS  -----------------------------------")
    print(request.headers)
    print("-----------------------------------------------------------------")
    
    
    print("-------------------- BODY  ---------------------------------------")
    print(request.body)
    error = ""
    
    try:
        if request.headers['Authorization'] == CALLBACK_ACCES:
            print("auth success")
            data = json.loads(request.body)
            
            headers = {"Authorization":data['ipn_token']} 
            
            res = requests.post(data['ipn'],headers=headers, data=json.dumps(data))
            print(">>>>>>>",res.json())
            if res.ok:
                return HttpResponse(json.dumps({"result":"received"}), mimetype,status=200)
        
    except Exception as e:
        print(e)
        
    
    
    return HttpResponse(json.dumps({"result":"access forbidden","e":error}), mimetype,status=403)


@csrf_exempt
def createCheckout(request):
    mimetype = 'application/json'
    try:
        
        data = json.loads(request.body)
        res = requests.post(HOST+"/api/v1/payment/checkout",headers=request.headers, data=data)
        print(res.json())
        return res.json()   
    except Exception as e:
        print(e)
        return HttpResponse(json.dumps({"result":"access forbidden","e":e}), mimetype,status=500)
    


def test(request):

    # data =
    # header = 
    r = requests.post("https://myapiv1.upgroup-pay.com/api/v1/payment/checkout",data=json.dumps(
        {
            "k_id": "ae9061ce15290cebe4ccd175784f7e510c21423e8ae9fb121d64112fa1834c43",
            "k_secret":"65c6c514a8fbd0d83b55f23f79b4cabdbe29ebfa6f02589d1eb0ec4341ba645c",
            "image": "",
            "products": [
                {
                "id": "5486455468",
                "price": "20000",
                "name": "Paiment facture mois septembre,",
                "qte": 1
                }
            ],
            "fields": {},
            "is_prod": False,
            "ipn": "https://dessdie.com",
            "ipn_token": "",
            "success": "https://dessdie.com",
            "cancel": "https://dessdie.com"
            }
    ),headers={"content-type":"application/json"})

    print(r.text)
    
    return JsonResponse({"res":r.text})