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))

[((382, 412), 'lnbits.core.core_app.route', 'core_app.route', (['"""/lnurlwallet"""'], {}), "('/lnurlwallet')\n", (396, 412), False, 'from lnbits.core import core_app\n'), ((961, 1103), 'requests.get', 'requests.get', (['withdraw_res.callback.base'], {'params': "{**withdraw_res.callback.query_params, **{'k1': withdraw_res.k1, 'pr':\n    payment_request}}"}), "(withdraw_res.callback.base, params={**withdraw_res.callback.\n    query_params, **{'k1': withdraw_res.k1, 'pr': payment_request}})\n", (973, 1103), False, 'import requests\n'), ((757, 807), 'lnbits.settings.WALLET.create_invoice', 'WALLET.create_invoice', (['withdraw_res.max_sats', 'memo'], {}), '(withdraw_res.max_sats, memo)\n', (778, 807), False, 'from lnbits.settings import WALLET\n'), ((901, 951), 'flask.abort', 'abort', (['Status.INTERNAL_SERVER_ERROR', 'error_message'], {}), '(Status.INTERNAL_SERVER_ERROR, error_message)\n', (906, 951), False, 'from flask import abort, redirect, request, url_for\n'), ((1148, 1220), 'flask.abort', 'abort', (['Status.INTERNAL_SERVER_ERROR', '"""Could not process withdraw LNURL."""'], {}), "(Status.INTERNAL_SERVER_ERROR, 'Could not process withdraw LNURL.')\n", (1153, 1220), False, 'from flask import abort, redirect, request, url_for\n'), ((1271, 1309), 'lnbits.settings.WALLET.get_invoice_status', 'WALLET.get_invoice_status', (['checking_id'], {}), '(checking_id)\n', (1296, 1309), False, 'from lnbits.settings import WALLET\n'), ((1318, 1326), 'time.sleep', 'sleep', (['i'], {}), '(i)\n', (1323, 1326), False, 'from time import sleep\n'), ((1697, 1747), 'flask.url_for', 'url_for', (['"""core.wallet"""'], {'usr': 'user.id', 'wal': 'wallet.id'}), "('core.wallet', usr=user.id, wal=wallet.id)\n", (1704, 1747), False, 'from flask import abort, redirect, request, url_for\n'), ((512, 541), 'flask.request.args.get', 'request.args.get', (['"""lightning"""'], {}), "('lightning')\n", (528, 541), False, 'from flask import abort, redirect, request, url_for\n'), ((616, 688), 'flask.abort', 'abort', (['Status.INTERNAL_SERVER_ERROR', '"""Could not process withdraw LNURL."""'], {}), "(Status.INTERNAL_SERVER_ERROR, 'Could not process withdraw LNURL.')\n", (621, 688), False, 'from flask import abort, redirect, request, url_for\n')]