from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.core.mail import send_mail

import xml.etree.ElementTree as ET

from datetime import datetime

import requests
import urllib.parse

from users.models import Client
from users.forms import ClientForm
from services.models import Service
from services.models import get_active
from .models import Order



from bot.bot import WEBHOOK_HOST
from bot.bot import bot

import kkb

from kkb.kkb_sign import KKBSign


def get_client(email):
    try:
        client = Client.objects.get(email=str(email))
        return client
    except:
        return None

def payment(request):
    service = get_active()
    if not service:
        return redirect('no_services')

    context = {}
    form = ClientForm()

    if request.method == 'POST':
        email = request.POST['email']
        client = get_client(email)

        form = ClientForm(request.POST)

        if client:
            form = ClientForm(request.POST, instance=client)

        if form.is_valid():
            form.save()
            return redirect('epay', email=request.POST['email'])
        else:
            form = ClientForm()
            

    context['form'] = form
    context['price'] = service.price
    context['name'] = service.name
    return render(request, 'payment/payment.html', context)


def invalid_token(request):
    return render(request, 'payment/invalid_token.html')

def no_services(request):
    return render(request, 'payment/no_services.html')

def no_user(request):
    return render(request, 'payment/no_user.html')

def epay(request, email=None):
    service = get_active()
    if not service:
        return redirect('no_services')
    client = get_client(email)
    if not email or not client:
        return redirect('no_user')

    client = Client.objects.get(email=email)
    o_id = Order.get_max()
    order = Order(email=email, client=client, order_id=o_id, service=service)
    order.save()

    context = kkb.get_context(order_id = str(order.order_id),amount=str(service.price))

    return render(request, 'payment/epay.html', {
        'context' :context,
        'post_link': f'https://{WEBHOOK_HOST}/payment/status',
        'back_link': f'https://{WEBHOOK_HOST}/',
        'email': email
    })



@csrf_exempt
def payment_status(request):
    try:
        if request.method == 'POST':
            
            response = request.POST['response']
            root = ET.fromstring(response)
            bank = root.find('bank')
            customer = bank.find('customer')
            merchant = customer.find('merchant')
            order = merchant.find('order')
            department = order.find('department')
            results = bank.find('results')
            payment = results.find('payment')

            order_id = order.get('order_id')
            merchant_id = department.get('merchant_id')
            reference = payment.get('reference')    
            approve_code = payment.get('approval_code')

            temp_order = Order.objects.get(order_id=order_id)

            amount = str(temp_order.service.price)
            currency = '398'
            try:
                rendered = f'<merchant id="{merchant_id}"><command type="complete"/><payment reference="{reference}" approval_code="{approve_code}" orderid="{order_id}" amount="{amount}" currency_code="{currency}"/></merchant>'
                kkbSign = KKBSign()
                result_sign = "".join(['<merchant_sign type="RSA" cert_id="',settings.MERCHANT_CERTIFICATE_ID, '">',kkbSign.sign64(rendered).decode('utf-8'),'</merchant_sign>'])

                xml = "".join(["<document>",rendered,result_sign,"</document>"])

                requests.get(url=f'https://epay.kkb.kz/jsp/remote/control.jsp?{urllib.parse.quote(xml)}')
            except Exception as e:
                bot.send_message(981996435, str(e))


            if settings.MERCHANT_ID == merchant_id and int(payment.get('response_code')) == 0:
                order_id = order.get('order_id')
                email = customer.get('mail')

                order = Order.objects.get(order_id=order_id)
                order.payed_date = datetime.now()
                order.status = 'Оплачен'
                order.save()

                send_mail(
                    f'Транзакция: #{order_id}.',
                    f'Оплата успешно осуществлена. \n Перейдите по данной ссылке: \n https://{WEBHOOK_HOST}/order/{order.token}',
                    'no-reply@thefactory.kz',
                    [email],
                    fail_silently=False,
                )
    except Exception as e:
        bot.send_message(981996435, str(e))

    return HttpResponse(0)

def order_to_bot(request, token=None):
    if not token:
        return redirect('invalid_token') 

    try:
        order = Order.objects.get(token=token)
        if not order.is_active_link:
            return redirect('invalid_token')
        order.is_active_link = False
        order.save()

        
        client = order.client
        client.link_pressed_at = datetime.now()
        client.save()

        return redirect(f'http://t.me/payment_aron_bot?start={order.token}')
    except:
        return redirect('invalid_token')
