<script src="/static/vendor/jquery/jquery.min.js"></script>
<script src="/static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/static/vendor/jquery-easing/jquery.easing.min.js"></script>
<script src="/static/js/main.js"></script>
<script src="/static/js/noty.js"></script>

{% if request.path == '/wallet/loading' %}
<script type="text/javascript">
function check_status(){
  fetch('/wallet/status')
    .then((resp) => resp.json())
    .then(function(data) {
        console.log(JSON.stringify(data));

        // If we've created a wallet and volume, but not connected a container and are not restoring, attempt connecting
        if(data['created'] && data['volume'] && data['connected'] == false && data['restoring'] == false){
          fetch('/wallet/connect')
        }

        // If ...
        if(data['created'] && data['volume'] && data['connected']){
          window.setInterval(function(){
            window.location.href = "{{ url_for('wallet.dashboard') }}"
          }, 3000);
        }
    })
}

// Check every few seconds...
window.setInterval(function(){
  check_status();
}, 6000);

// ...but also check on initial page load
check_status();

</script>
{% endif %}

{% if request.path == '/wallet/dashboard' %}
<script type="text/javascript" src="/static/js/zxing.js"></script>
<script type="text/javascript">

  function decodeOnce(codeReader, selectedDeviceId) {
    codeReader.decodeFromInputVideoDevice(selectedDeviceId, 'video').then((result) => {
      const url = new URL(result.text);
      if (url.protocol == 'wownero:'){
        document.getElementById('address').value = url.pathname;
        url.searchParams.forEach((value, key) => {
          if (key == 'tx_amount'){
            document.getElementById('amount').value = value;
          };
        });
      };
      codeReader.reset();
      $('#preview').hide();
    }).catch((err) => {
      console.error(err);
      codeReader.reset();
      $('#preview').hide();
    })
  }

  window.addEventListener('load', function () {
    let selectedDeviceId;
    const codeReader = new ZXing.BrowserQRCodeReader();
    codeReader.getVideoInputDevices()
      .then((videoInputDevices) => {
        document.getElementById('startVideo').addEventListener('click', () => {
          $('#preview').show();
          decodeOnce(codeReader, videoInputDevices[0].deviceId);
        })
        document.getElementById('stopVideo').addEventListener('click', () => {
          codeReader.reset();
          $('#preview').hide();
        })
      })
      .catch((err) => {
        console.error(err)
      })
  })
</script>
{% endif %}

{% with messages = get_flashed_messages() %}
  {% if messages %}
  <script type="text/javascript">
    {% for message in messages %}
    new Noty({
      type: 'warning',
      theme: 'relax',
      layout: 'topCenter',
      text: '{{ message }}',
      timeout: 3500
    }).show();
    {% endfor %}
  </script>
  {% endif %}
{% endwith %}
