<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
  <title>Johoe's Lightning Donation Page</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <link href="style.css" rel="stylesheet" type="text/css"/>
  <script src="qrcodegen.min.js"></script>
</head>
<body onload="loadDoc()">
<div class="tab">
  <button class="tablinks" onclick="selectTab(event.currentTarget, 'channel')">Open Channel</button>
  <button id="btninvoice" class="tablinks" onclick="selectTab(event.currentTarget, 'invoice')">Payment Request</button>
  <button id="defaulttab" class="tablinks" onclick="selectTab(event.currentTarget, 'setamount')">Set Amount</button>
</div>
<div id="channel" class="tabcontent" onclick="copyclipboard('textnode')">
   <p>Scan this QRCode to open a channel to my node. Click to copy to clipboard.</p>
   <div class="lncontainer"><canvas id="qrnode" class="lnqrcode"></canvas></div>
   <textarea id="textnode" class="lntext" rows="2"></textarea>
</div>
<div id="invoice" class="tabcontent">
   <p>Scan or click this QRCode to start a payment.</p>
   <div class="lncontainer">
     <div id="qrwait" class="lnwait">creating payment request<br/>please wait...</div>
     <a id="qrlink" href="#"><canvas id="qrinvoice" class="lnqrcode"></canvas></a>
     <div id="qrpayed" class="lnsettled">PAID<br/>Thank You</div>
   </div>
   <textarea id="textinvoice" rows="5" class="lntext"></textarea>
   <input type="button" value="Copy to Clipboard"
    onclick="copyclipboard('textinvoice')"/>
</div>
<div id="setamount" class="tabcontent">
   Pay for server time <span class="footnotebox"><a href="#" onclick="toggle('footnote1')">[*]</a><span id="footnote1" class="footnote" style="display:none;">
   Server cost is 90 €/month.<br/>
   So one day costs 3 €.
</span></span>:
   <input type="button" value="1 hour" onclick="setvalue(.13, 'EUR')" />
   <input type="button" value="1 day" onclick="setvalue(3.00, 'EUR')" />
   <input type="button" value="1 week" onclick="setvalue(21.00, 'EUR')" />
   <input type="button" value="1 month" onclick="setvalue(90.00, 'EUR')" /><br/>
   <p>Amount: <input type="number" id="value" value="" onchange="updateValue()" style="text-align:right;" />
     <select id="unit" value="sat" onchange="updateValue()">
       <option value="sat">sat</option>
       <option value="bit">bit</option>
       <option value="USD">USD</option>
       <option value="EUR">EUR</option>
       <option value="BTC">BTC</option>
     </select></p>
   <p style="text-align:right;"> =
     <span id="btcvalue">0</span> BTC
     (<span id="factor">1</span> <span id="unit2">BTC</span>/BTC).</p>
   <p>Memo: <input type="text" id="memo" size="30" value="Donation for Johoe's mempool" /></p>
   <input type="button" value="Get invoice" onclick="invoice()" />
</div>
<script>
  var btceur = 10138;
  var btcusd = 11397;
  var valueinsat = 0;
  var border = 4;
  var scale = 4;
  var uri = "0358327cb80ab2a8db36a5924c62966c7b4a753045600df594aa3863ecb618cc5d@88.198.39.205:9735";
  var qruri = qrcodegen.QrCode.encodeText(uri, qrcodegen.QrCode.Ecc.MEDIUM);
  qruri.drawCanvas(scale, border, document.getElementById("qrnode"));
  document.getElementById("textnode").value = uri;
  var paymentrhash;

  function setvalue(value, unit) {
    document.getElementById("value").value = value;
    document.getElementById("unit").value = unit;
    updateValue();
  }

  function updateValue() {
    var value = document.getElementById("value").value;
    var unit = document.getElementById("unit").value;
    var factor = 1.0;
    switch(unit) {
    case "BTC":
      factor = 1.0;
      break;
    case "EUR":
      factor = btceur;
      break;
    case "USD":
      factor = btcusd;
      break;
    case "bit":
      factor = 1000000.0;
      break;
    case "sat":
      factor = 100000000.0;
      break;
    }
    valueinsat = Math.floor((value * 100000000.0 / factor) + 0.5);
    document.getElementById("btcvalue").innerHTML = (valueinsat/100000000.0).toFixed(8);

    document.getElementById("factor").innerHTML = factor;
    document.getElementById("unit2").innerHTML = unit;
  }

  function invoice() {
    var value = ~~valueinsat;
    var memo = document.getElementById("memo").value;
    if (value < 0) {
      alert("Nice try :) Please enter a positive value");
      return;
    }
    if (value > 4294967) {
      alert("Please keep amount to less than 0.04 BTC");
      return;
    }
    requestInvoice(value, memo);
    selectTab(document.getElementById("btninvoice"), "invoice");
  }

  function waitfor(rhash) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      if (rhash != paymentrhash) {
         return;
      }
      if (this.readyState == 4) {
         if (this.status == 200) {
            var response = JSON.parse(this.responseText);
            if (!response.settled) { 
               waitfor(rhash);
            } else {
               document.getElementById("qrinvoice").style.opacity = 0.2;
               document.getElementById("qrpayed").style.display = "block";
            }
         } else if (this.status != 0) {
            alert("Cannot check payment status: "+ this.status + " state: "+this.readyState+"text: "+this.responseText);
         }
      }
    }
    xhttp.open("POST", "/lnd/check-invoice.py?r_hash="+rhash, true);
    xhttp.send();
  }

  function requestInvoice(value, memo) {
    document.getElementById("qrwait").style.display = "block";
    document.getElementById("qrlink").href = "#";
    document.getElementById("textinvoice").value = "";
    var canvas = document.getElementById("qrinvoice");
    var context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);
    paymentrhash = 0;

    var xhttp = new XMLHttpRequest();
    function handleInvoice(invoice) {
       var rhash = invoice.r_hash;
       paymentrhash = rhash;
       paymentrequest = invoice.payment_request;
       var qrcode = qrcodegen.QrCode.encodeText(paymentrequest.toUpperCase(), qrcodegen.QrCode.Ecc.LOW);
       document.getElementById("qrwait").style.display = "none";
       qrcode.drawCanvas(scale, border, document.getElementById("qrinvoice"));
       document.getElementById("qrlink").href = "lightning:" + paymentrequest;
       document.getElementById("textinvoice").value = paymentrequest;
       waitfor(rhash);
    }

    xhttp.onreadystatechange = function() {
      if (this.readyState == 4) {
         if (this.status == 200) {
            handleInvoice(JSON.parse(this.responseText));
         } else {
            document.getElementById("textinvoice").value = "Failed to get payment request";
         }
      }
    }
    var params = "memo="+encodeURIComponent(memo)+"&value="+~~value;
    xhttp.open("POST", "/lnd/invoice.py?"+params, true);
    xhttp.send();
  }

  var xhttpbtc = new XMLHttpRequest();
  xhttpbtc.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      var response = JSON.parse(this.responseText);
      btcusd = response.bpi.USD.rate_float;
      btceur = response.bpi.EUR.rate_float;
      updateValue();
    }
  }
  function loadDoc() {
    var donationfor = "Johoe's mempool";
    if (location.hash.length > 0) {
        donationfor = location.hash.substring(1);
    }
    document.getElementById("memo").value = "Donation for " + donationfor;
    requestInvoice(0, "Donation to " + donationfor);
    xhttpbtc.open("GET", "https://api.coindesk.com/v1/bpi/currentprice.json", true);
    xhttpbtc.send();
    updateValue();
  }

  function selectTab(button, name) {
    // Declare all variables
    var i, tabcontent, tablinks;

    // Get all elements with class="tabcontent" and hide them
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }

    // Get all elements with class="tablinks" and remove the class "active"
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }

    // Show the current tab, and add an "active" class to the button that opened the tab
    document.getElementById(name).style.display = "block";
    button.className += " active";
  }

  function copyclipboard(id) {
    var copyText = document.getElementById(id);
    copyText.select();
    document.execCommand("copy");
  }

  function toggle(id) {
    var block = document.getElementById(id);
    var count = 0;
    if (block.style.display == "none") {
      block.style.display="block";
      var hidefootnote = function (event) {
        if (count++ >= 1) {
          block.style.display="none";
          document.removeEventListener('click', hidefootnote);
        }
      };
      document.addEventListener('click', hidefootnote);
    }
  }
  document.getElementById("defaulttab").click();
</script>
  <div class="centered" style="font-size: 13px; margin: 20px;">
     Source code on github: <a href="https://github.com/jhoenicke/mempool/tree/master/web/lightning/" target="_blank">https://github.com/jhoenicke/mempool</a><br/>
     © 2018 <a href="https://jochen-hoenicke.de/">Jochen Hoenicke</a>
  </div>
</body>
</html>
