<!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="vendor/jquery-3.4.1.min.js"></script>
    <script type="text/javascript" src="vendor/jquery-ui.min.js"></script>
    <script type="text/javascript" src="vendor/qrcode.js"></script>
    <link rel="stylesheet" type="text/css"
          href="vendor/jquery-ui-themes-1.12.1/themes/ui-lightness/jquery-ui.css">
    <style type="text/css">

      body {
	  font-family: Arial;
      }

      .tab {
	  overflow: hidden;
	  border: 1px solid #ccc;
	  background-color: #f1f1f1;
      }
      .tab button {
	  background-color: inherit;
	  float: left;
	  border: none;
	  outline: none;
	  cursor: pointer;
	  padding: 14px 16px;
	  transition: 0.3s;
      }
      .tab button:hover {
	  background-color: #ddd;
      }
      .tab button.active {
	  background-color: #ccc;
      }
      .tabcontent {
	  padding: 6px 12px;
	  border: 1px solid #ccc;
	  border-top: none;
      }
      .column {
	  float: left;
	  width: 50%;
      }
      .row{
	  padding: 26px 26px;
	  border: 1px solid #ccc;
      }
      .row:after {
	  content: "";
	  display: table;
	  clear: both;
      }
      .paybutton{
	  width:100%;
	  background-color:#ccc;
	  border-radius: 5px;
	  padding:10px;
      }
      #payreq{
	  overflow-wrap: break-word;
      }
      #progressbar {
	  position: relative;
	  background: #555;
      }
      .progress-label {
	  position: absolute;
	  top: 8px;
	  color: #fff;
	  font-weight: bold;
	  text-shadow: 1px 1px 0 #000;
      }
    </style>
</head>
<body>
    <div style="width:20em; margin:auto; font-family:arial, serif;">
        <div class="error" id="error"></div>
        <div id="container">
	  <div id="progressbar">
	    <div class="progress-label" style="left: 5%;" id="progress-text"></div>
	    <div class="progress-label" style="right: 5%;" id="progress-timer"></div>
	  </div>
	  <div class="row">
	    <div id="reason" style="float:left; width:50%"></div>
	    <div id="amount" style="float:right; width:50%"></div>
	  </div>
	  <!-- Tab content -->
	  <div id="lightning" class="tabcontent">
            <div id="qr" align="center"></div>
            <div id="payreq" align="left"></div>
	    <br/>
            <div class="error" id="lnerror" style="height:15em; text-align:justify; display:none;"></div>
            <div>
              <button class="paybutton">
                <a style="color:#000; text-decoration:none;" id="paylink" target="_blank">Open in Wallet</a>
              </button>
	    </div>
	    <div>
              <button id="copy" class="paybutton" onclick="doCopy(this.value)" value="">
                Copy Request
              </button>
            </div>
	  </div>
          <p id="powered" style="font-size:80%;"></p>
        </div>
    </div>
    <script type="text/javascript">

function doCopy(text){
    navigator.clipboard.writeText(text);
    alert("Copied to Clipboard: " + text);
}

function paymentExpired(){
    $(".tabcontent").hide();
    $(".tablinks").removeClass("active");
    $("#progress-text").html("This invoice has expired");
    $(".ui-widget-header").css("background", "#f33");
}

function paymentReceived(){
    $(".tabcontent").hide();
    $(".tablinks").removeClass("active");
    $("#progress-text").html("Payment received.");
    $(".ui-widget-header").css("background", "#0a0");
    payment_received = true;
    $("#progress-timer").text("");
    $("#progressbar").progressbar({
	value: 100,
	max: 100
    });
}
function paymentUnknown(){
    $("#progress-text").html('Error: Unknown invoice');
    $("#progressbar").progressbar({
	value: 100,
	max:100
    });
    $(".ui-widget-header").css("background", "#f33");
}

/* AI generated code: This function was written by ChatGPT. Copyright is dubious!!! */
function formatTime(timeInSeconds) {
    var hours = Math.floor(timeInSeconds / 3600);
    var minutes = Math.floor((timeInSeconds - (hours * 3600)) / 60);
    var seconds = timeInSeconds - (hours * 3600) - (minutes * 60);
    if (hours < 10) {
        hours = "0" + hours;
    }
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (seconds < 10) {
        seconds = "0" + seconds;
    }
    return hours + ":" + minutes + ":" + seconds;
}
/* end of AI generated code */

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');
var payment_received = false;

if (id) {
    var jqxhr = $.getJSON("/api/get_invoice?" +  id, function() {
        console.log("getJSON:success");
    })
	.done(function(data) {
	    var typeNumber = 0;
	    var errorCorrectionLevel = 'L';
	    var URI;
	    var request;
	    var qr_text;
	    $("<p />").text("Powered by Electrum").appendTo($("p#powered"));
	    if(!data) {
		paymentUnknown();
		return;
	    }
	    if (data.is_lightning && !data.can_receive){
		$("#lnerror").text("Error: The server does not have enough inbound capacity to receive this amount with lightning. Try reloading this page later.");
		$(".tabcontent").hide();
		return;
	    }
	    if (data.is_lightning){
		request = data.lightning_invoice;
		URI = 'lightning:' + data.lightning_invoice;
		qr_text = request.toUpperCase();
	    }
	    else if (data.URI){
		request = data.URI;
		if (data.bip70_url) request += '&r=' + data.bip70_url;
		qr_text = request;
		URI = request;
	    }
	    else {
		request = data.address;
		qr_text = request;
		URI = 'bitcoin:' + data.address;
            }
            var qr = qrcode(typeNumber, errorCorrectionLevel);
            qr.addData(qr_text);
            qr.make();
            $("#payreq").text(URI);
            $("#qr").html(qr.createImgTag(3));
            $("#copy").val(request);
            $("#paylink").attr("href", URI);
            $("#error").hide();
            $("#reason").text(data.message || "no description");
            $("#amount").text(data.amount_BTC + " BTC");
            $(function () {
		var current;
		var max = 100;
		var initial = data.timestamp;
		var duration = data.expiration - data.timestamp;
		$("#progressbar").progressbar({
		    value: 100,
		    max:max
		});
		$("#progress-text").text("Awaiting payment...");
		if(data.expiration){
		    function update() {
			var seconds = (Math.floor(Date.now()/1000) - initial);
			var current = 100 * (seconds)/duration;
			var remaining = duration - seconds
			if(!payment_received){
			    $("#progressbar").progressbar({
				value: current,
				max:max
			    });
			    if (current < max) {
				$("#progress-timer").text(formatTime(remaining));
			    }
			}
		    };
		    update();
		    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') {
		    paymentReceived();
		}
		if(received_msg == 'expired') {
		    paymentExpired();
		}
            }
            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>
