{% load static %} {% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    {% block 'title' %}
    <title>{% if title %}{{ title|safe }}{% else %}{% trans "SEP24 reference server" %}{% endif %}</title>
    {% endblock %}

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Cabin&display=swap">
    <link rel="stylesheet" href="{% static 'polaris/base.css' %}" />
    <style>
      {% comment %}
      Due to the static image, can't put the background in .scss
      {% endcomment %}
      .control select:not([multiple]) {
        background-image: url("{% static "polaris/chevron-down.svg" %}");
        background-repeat: no-repeat;
        background-position: right 1em top 50%, 0 0;
      }
    </style>

    {% block 'extra_head' %}
    {% endblock %}
  </head>
  <body>
    {% block "header" %}
    <nav class="navbar" role="navigation" aria-label="main navigation">
      <div class="navbar-brand">
        {% if icon_path %}
        <img class="logo" src="{% static icon_path %}" alt="" />
        {% elif org_logo_url %}
        <img class="logo" src="{{ org_logo_url }}" alt="" />
        {% else %}
        <img class="logo" src="{% static 'polaris/company-icon.svg' %}" alt="" />
        {% endif %}
        {% if icon_label %}
        <a class="title" href="#">
            {{ icon_label|safe }}
        </a>
        {% endif %}
      </div>
    </nav>
    {% endblock %}
    <div class="main-content">
      {% block "content" %}
      {% endblock %}
    </div>
    <div class="bottom section">
      {% block "footer" %}
      {% endblock %}
    </div>
    <script type="text/javascript">
      "use strict";
      function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } }

      {% comment %}
      Manually babel-ized helper. Generic helper to wait until conditions are right.
      {% endcomment %}
      var waitFor = function waitFor(predicate) {
        var pollInterval = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 500;
        return new Promise(function (resolve) {
          var check = function check() {
            var result = predicate();
            if (_instanceof(result, Promise)) {
              result.then(function (isFinished) {
                if (isFinished) {
                  resolve();
                  return;
                }
                setTimeout(check, pollInterval);
              });
            } else {
              if (result) {
                resolve();
                return;
              }
              setTimeout(check, pollInterval);
            }
          };
          check();
        });
      };

      // Date/time pickers
      if (
        document.querySelector('input.date') !== null ||
        document.querySelector('input.date-time') !== null ||
        document.querySelector('input.time') !== null
      ) {
        var datepickerScript = document.createElement('script');
        datepickerScript.src = "https://unpkg.com/flatpickr@4.6.3/dist/flatpickr.min.js";
        datepickerScript.async = true;
        document.body.append(datepickerScript)

        var datepickerScript = document.createElement('script');
        datepickerScript.src = "https://unpkg.com/flatpickr@4.6.3/dist/l10n/{{ LANGUAGE_CODE }}.js";
        datepickerScript.async = true;
        document.body.append(datepickerScript)

        var datepickerScript = document.createElement('link');
        datepickerScript.href = "https://unpkg.com/flatpickr@4.6.3/dist/flatpickr.min.css";
        datepickerScript.rel = "stylesheet";
        document.head.append(datepickerScript)

        waitFor(function() {return !!window.flatpickr}).then(function () {
          window.flatpickr.localize(window.flatpickr.l10ns['{{ LANGUAGE_CODE }}']);
          window.flatpickr('input.date');
          window.flatpickr('input.date-time', {enableTime: true});
          window.flatpickr('input.time', {noCalendar: true, enableTime: true});
        })
      }

      // File picker
      document.querySelectorAll('.file-upload-field').forEach(function(f) {
        f.addEventListener('change', function(e) {
          var filename = e.target.value.replace(/.*(\/|\\)/, '') || 'Select a file';
          e.target.parentElement.setAttribute('data-text', filename);
        })
      })

      // Card inputs
      if (document.querySelector('.cc-number') !== null) {
        {% comment %} https://github.com/nosir/cleave.js {% endcomment %}
        var cleaveScript = document.createElement('script');
        cleaveScript.src = "https://unpkg.com/cleave.js@1.5.3/dist/cleave.min.js";
        cleaveScript.async = true;
        document.body.append(cleaveScript)

        waitFor(function() { return window.Cleave }).then(function() {
          new Cleave('.cc-number', { creditCard: true })
          new Cleave('.cc-expiration', { date: true, datePattern: ['m', 'y'] })
          new Cleave('.cc-cvv', {
            numeral: true,
            numeralThousandsGroupStyle: 'none',
            numericOnly: true,

          })
        })
      }

      // Disable form submit buttons after first click
      let submitButton = document.querySelector('.submit');
      let anchorForm = document.querySelector('form');
      if (anchorForm) {
        anchorForm.addEventListener('submit', (e) => {
          submitButton.disabled = true;
        });
      }

      // Show fee and amount user will receive when amount field
      // changes, if present.
      let amountInput = document.querySelector('.amount-input');
      let feeTag = document.querySelector('.fee');
      let amountOutTag = document.querySelector('.amount-out');
      if (amountInput) {
        let feeTable = document.querySelector('.fee-table');
        feeTable.removeAttribute('hidden');
        amountInput.addEventListener("input", (e) => {
          if (isNaN(e.target.value)) return;
          let fee_fixed;
          let fee_percent;
          let amountIn = Number(e.target.value);
          if (amountIn === 0) {
            // The user is likely deleting all characters.
            // Wait a bit for the last fetch() call to resolve,
            // so its results don't overwrite this 0.
            setTimeout(() => {
              feeTag.innerHTML = "{{ asset.symbol }}" + "0";
              amountOutTag.innerHTML = "{{ asset.symbol }}" + "0";
            }, 100);
            return;
          }
          let op = "{{ operation }}";
          if (op === "deposit") {
            fee_fixed = {{ asset.deposit_fee_fixed|default:0 }}
            fee_percent = {{ asset.deposit_fee_percent|default:0 }}
          } else {
            fee_fixed = {{ asset.withdrawal_fee_fixed|default:0 }}
            fee_percent = {{ asset.withdrawal_fee_percent|default:0 }}
          }
          let fee;
          let amountOut;
          if ("{{ use_fee_endpoint }}" !== "True") {
            fee = fee_fixed + (amountIn * (fee_percent/100));
            amountOut = amountIn - fee;
          } else {
            // Need to hit fee endpoint
            let params = new URLSearchParams();
            params.append("operation", op);
            params.append("asset_code", "{{ asset.code }}");
            params.append("amount", amountIn);
            fetch("/sep24/fee?" + params.toString()).then(
              response => response.json()
            ).then(json => {
               if (!json.error) {
                 fee = json.fee;
                 amountOut = amountIn - json.fee;
               }
            });
          }
          function calcFee() {
            let feeVal = fee.toFixed({{ asset.significant_decimals }});
            let amountOutVal = amountOut.toFixed({{ asset.significant_decimals }});
            feeTag.innerHTML = "{{ asset.symbol }}" + ((Number(feeVal) === 0) ? "0" : feeVal);
            amountOutTag.innerHTML = "{{ asset.symbol }}" + ((Number(amountOutVal) === 0) ? "0" : amountOutVal);
          }
          function waitForAmountOut() {
            if (!amountOut) {
              setTimeout(waitForAmountOut, 100);
            } else {
              calcFee();
            }
          }
          if (!amountOut) {
            setTimeout(waitForAmountOut, 100);
          } else {
            calcFee();
          }
        });
      }
    </script>

    {# Rendered via Polaris javascript integrations #}
    {% for script in scripts %}
      {% if script.path %}
      <script src="/static/{{ script.path }}" {% if script.is_async %}async{% endif %} ></script>
      {% elif script.url %}
      <script src="{{ script.url }}" {% if script.is_async %}async{% endif %}></script>
      {% endif %}
    {% endfor %}

    {# Rendered via custom extra_body template #}
    {% block 'extra_body' %}
    {% endblock %}

  </body>
</html>
