import requests

from flask import abort, redirect, request, url_for
from lnurl import LnurlWithdrawResponse, handle as handle_lnurl
from lnurl.exceptions import LnurlException
from time import sleep

from lnbits.core import core_app
from lnbits.helpers import Status
from lnbits.settings import WALLET

from ..crud import create_account, get_user, create_wallet, create_payment


@core_app.route("/lnurlwallet")
def lnurlwallet():
    memo = "LNbits LNURL funding"

    try:
        withdraw_res = handle_lnurl(request.args.get("lightning"), response_class=LnurlWithdrawResponse)
    except LnurlException:
        abort(Status.INTERNAL_SERVER_ERROR, "Could not process withdraw LNURL.")

    try:
        ok, checking_id, payment_request, error_message = WALLET.create_invoice(withdraw_res.max_sats, memo)
    except Exception as e:
        ok, error_message = False, str(e)

    if not ok:
        abort(Status.INTERNAL_SERVER_ERROR, error_message)

    r = requests.get(
        withdraw_res.callback.base,
        params={**withdraw_res.callback.query_params, **{"k1": withdraw_res.k1, "pr": payment_request}},
    )

    if not r.ok:
        abort(Status.INTERNAL_SERVER_ERROR, "Could not process withdraw LNURL.")

    for i in range(10):
        invoice_status = WALLET.get_invoice_status(checking_id)
        sleep(i)
        if not invoice_status.paid:
            continue
        break

    user = get_user(create_account().id)
    wallet = create_wallet(user_id=user.id)
    create_payment(
        wallet_id=wallet.id,
        checking_id=checking_id,
        amount=withdraw_res.max_sats * 1000,
        memo=memo,
        pending=invoice_status.pending,
    )

    return redirect(url_for("core.wallet", usr=user.id, wal=wallet.id))

[((15, 1, 15, 31), 'lnbits.core.core_app.route', 'core_app.route', ({(15, 16, 15, 30): '"""/lnurlwallet"""'}, {}), "('/lnurlwallet')", False, 'from lnbits.core import core_app\n'), ((32, 8, 35, 5), 'requests.get', 'requests.get', (), '', False, 'import requests\n'), ((25, 58, 25, 108), 'lnbits.settings.WALLET.create_invoice', 'WALLET.create_invoice', ({(25, 80, 25, 101): 'withdraw_res.max_sats', (25, 103, 25, 107): 'memo'}, {}), '(withdraw_res.max_sats, memo)', False, 'from lnbits.settings import WALLET\n'), ((30, 8, 30, 58), 'flask.abort', 'abort', ({(30, 14, 30, 42): 'Status.INTERNAL_SERVER_ERROR', (30, 44, 30, 57): 'error_message'}, {}), '(Status.INTERNAL_SERVER_ERROR, error_message)', False, 'from flask import abort, redirect, request, url_for\n'), ((38, 8, 38, 80), 'flask.abort', 'abort', ({(38, 14, 38, 42): 'Status.INTERNAL_SERVER_ERROR', (38, 44, 38, 79): '"""Could not process withdraw LNURL."""'}, {}), "(Status.INTERNAL_SERVER_ERROR, 'Could not process withdraw LNURL.')", False, 'from flask import abort, redirect, request, url_for\n'), ((41, 25, 41, 63), 'lnbits.settings.WALLET.get_invoice_status', 'WALLET.get_invoice_status', ({(41, 51, 41, 62): 'checking_id'}, {}), '(checking_id)', False, 'from lnbits.settings import WALLET\n'), ((42, 8, 42, 16), 'time.sleep', 'sleep', ({(42, 14, 42, 15): 'i'}, {}), '(i)', False, 'from time import sleep\n'), ((57, 20, 57, 70), 'flask.url_for', 'url_for', (), '', False, 'from flask import abort, redirect, request, url_for\n'), ((20, 36, 20, 65), 'flask.request.args.get', 'request.args.get', ({(20, 53, 20, 64): '"""lightning"""'}, {}), "('lightning')", False, 'from flask import abort, redirect, request, url_for\n'), ((22, 8, 22, 80), 'flask.abort', 'abort', ({(22, 14, 22, 42): 'Status.INTERNAL_SERVER_ERROR', (22, 44, 22, 79): '"""Could not process withdraw LNURL."""'}, {}), "(Status.INTERNAL_SERVER_ERROR, 'Could not process withdraw LNURL.')", False, 'from flask import abort, redirect, request, url_for\n')]