<!DOCTYPE HTML>
<html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      <title>Payment request</title>
        <script type="text/javascript" charset="utf-8"
            src="jquery-3.4.1.min.js">
        </script>
        <script type="text/javascript"
            src="jquery-ui.min.js">
        </script>
        <script type="text/javascript"
            src="qrcode.js">
        </script>
        <link rel="stylesheet" type="text/css"
            href="jquery-ui-themes-1.12.1/themes/trontastic/jquery-ui.min.css">
    </head>
    <body>
      <div style="width:25em; margin:auto; font-family:arial, serif;">
        <h2>Bitcoin Payment</h2>
        <p id="status"></p>
        <p id="error"></p>
        <h3>Amount: <span id="amount"></span></h3>
        <h3>Description: <span id="reason"></span></h3>
	<div id="container">
          <div id="progressbar"></div>
          <br/>
	  <div>
            <div style="background-color:#7777aa; border-radius: 5px; padding:10px;">
              <a style="color:#ffffff; text-decoration:none;" id="paylink" target="_blank">Click here to pay</a>
            </div>
	  </div>
          <p id="powered" style="font-size:80%;"></p>
          <br/>
	  <h3>Payment Request:</h3>
	  <div id="payreq" style="word-break: break-word; color:#808080;"></div>
	  <h3>QR Code:</h3>
          <div id="qrcode" align="center"></div>
	  <br/>
	</div>
      </div>
	
<script type="text/javascript">

function getUrlParameter(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++)
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam)
        {
            return sParameterName[1];
        }
    }
}

var id = getUrlParameter('id');

if (id) {
    var jqxhr = $.getJSON("/api/get_invoice?" +  id, function() {
        console.log("getJSON:success");
    })
    .done( function(data) {
	var qrcode = new QRCode(document.getElementById("qrcode"), {width:400, height:400});
	var URI;
	var request;
	if (data.is_lightning){
		request = data.invoice;
		URI = 'lightning:' + request;
		qrcode.makeCode(data.invoice.toUpperCase());
	} else {
		URI = data.URI;
		if (data.bip70_url) URI += '&r=' + data.bip70_url;
		request = URI;
		qrcode.makeCode(URI);
	}
	$("#payreq").text(request);
	$("#reason").text(data.message);
        $("#amount").text(data.amount_BTC + " BTC");
        $("#paylink").attr("href", URI);
        $("<p />").text("Powered by Electrum").appendTo($("p#powered"));
        $(function () {
            var current;
            var max = 100;
            var initial = data.timestamp;
            var duration = data.expiration;
            if(duration){
                   var current = 100 * (Math.floor(Date.now()/1000) - initial)/duration;
              $("#progressbar").progressbar({
                value: current,
                max: max
              });
              function update() {
                current = 100 * (Math.floor(Date.now()/1000) - initial)/duration;
                $("#progressbar").progressbar({
                    value: current
                });
                if (current >= max) {
                    $("#container").html("This invoice has expired");
                }
              };
              var interval = setInterval(update, 1000);
             }
        });

        var wss_address = (document.URL.startsWith("https") ? "wss" : "ws") + "://" + window.location.host +"/api/get_status?" + id;
        console.log("Opening WSS: " + wss_address)
        var ws = new WebSocket(wss_address);
        var received_msg;

        ws.onmessage = function (evt) {
            received_msg = evt.data;
            if(received_msg == 'paid'){
                $("#container").html("This invoice has been paid.");
            }
            if(received_msg == 'expired'){
                $("#container").html("This invoice has expired.");
            }
            /*else $("#status").html(received_msg);*/
        }
        ws.onerror = function () {
            console.log("error ws.onerror");
            $("#error").text("error with websocket. try reloading this page");
        };
        ws.onclose = function () {
            console.log("error ws.onclose");
            if(received_msg == 'waiting')
              $("#error").text("error with websocket: socket was closed. try reloading this page");
        };

    })
    .fail(function() {
        console.log("error fail while fetching invoice json");
        $("#error").text("error while fetching invoice json. try reloading this page");
    });
};

// See http://stackoverflow.com/questions/29186154/chrome-clicking-mailto-links-closes-websocket-connection
$(document).on('click', 'a[href^="bitcoin:"]', function (e) {
    e.preventDefault();
    var btcWindow = window.open($(e.currentTarget).attr('href'));
    btcWindow.close();
    return false;
});

</script>
  
    </body>
</html>
