{% extends "kfet/base_col_1.html" %}
{% load static %}

{% block extra_head %}
<link rel="stylesheet" type="text/css" href="{% static 'kfet/css/transfers_form.css' %}">
<script type="text/javascript" src="{% url 'js_reverse' %}" ></script>
{% endblock %}

{% block title %}Nouveaux transferts{% endblock %}
{% block header-title %}Création de transferts{% endblock %}

{% block main-size %}col-sm-12{% endblock %}

{% block main %}

<form id="transfers_form">
  {% csrf_token %}
  <div class="transfer_general text-center">
    <input type="text" name="comment" id="comment" placeholder="Commentaire"><!--
    --><button type="submit" id="submit" class="btn btn-primary btn-lg">Enregistrer</button>
    {{ transfer_formset.management_form }}
  </div>
  <table class="transfer_formset table" id="transfer_formset">
    <thead>
      <tr>
        <td></td>
        <td>De</td>
        <td><span class="glyphicon glyphicon-euro"></span></td>
        <td>Vers</td>
        <td></td>
      </tr>
    </thead>
    <tbody>
      {% for form in transfer_formset %}
        <tr class="transfer_form" id="{{ form.prefix }}">
          <td class="from_acc_data"></td>
          <td class="from_acc">
            <input type="text" name="from_acc" class="input_from_acc" maxlength="3" autocomplete="off" spellcheck="false">
            {{ form.from_acc }}
          </td>
          <td class="amount">{{ form.amount }}</td>
          <td class="to_acc">
            <input type="text" name="to_acc" class="input_to_acc" maxlength="3" autocomplete="off" spellcheck="false">
            {{ form.to_acc }}
          </td>
          <td class="to_acc_data"></td>
        </tr>
      {% endfor %}
    </tbody>
  </table>
</form>

<script type="text/javascript">
$(document).ready(function () {

    function getAccountData(trigramme, callback = function() {}) {
        $.ajax({
            dataType: "json",
            url     : django_urls["kfet.account.read.json"]({trigramme: encodeURIComponent(trigramme)}),
            method  : "GET",
            success : callback,
        });
    }

    function updateAccountData(trigramme, $input) {
        var $form = $input.closest('.transfer_form');
        if ($input.attr('name') == 'from_acc') {
            var $data = $form.find('.from_acc_data');
            var $next = $form.find('.amount input');
        } else {
            var $data = $form.find('.to_acc_data');
            var $next = $form.next('.transfer_form').find('.from_acc input');
        }
        var $input_id = $input.next('input');
        if (trigramme.is_valid_trigramme()) {
            getAccountData(trigramme, function(data) {
                $input_id.val(data.id);
                $data.text(data.name);
                if (!$next.length) {
                  new_row = add_form();
                  new_row.find(".from_acc input").focus();
                } else {
                  $next.focus();
                }
            });
        } else {
            $input_id.val('');
            $data.text('');
        }
    }

    $(document).on("input", '.input_from_acc, .input_to_acc', function(e) {
        var target = $(e.target)
        var tri = target.val().toUpperCase();
        updateAccountData(tri, target);
    });

    $('#transfers_form').on('submit', function(e) {
        e.preventDefault();
        performTransfers();
    });

    function performTransfers(password = '') {
        var data = $('#transfers_form').serialize();
        $.ajax({
            dataType: "json",
            url     : "{% url 'kfet.transfers.perform' %}",
            method  : "POST",
            data    : data,
            beforeSend: function ($xhr) {
                if (password != '')
                    $xhr.setRequestHeader("KFetPassword", password);
            },
        })
        .done(function(data) {
            window.location.href = "{% url 'kfet.transfers' %}";
        })
        .fail(function($xhr) {
            var data = $xhr.responseJSON;
            switch ($xhr.status) {
                case 403:
                    requestAuth(data, performTransfers);
                    break;
                case 400:
                    displayErrors(data);
                    break;
            }
        });
    }

    function add_form() {
      var row_template = `
      <tr class="transfer_form" id="{{ transfer_formset.empty_form.prefix }}">
        <td class="from_acc_data"></td>
        <td class="from_acc">
          <input type="text" name="from_acc" class="input_from_acc" maxlength="3" autocomplete="off" spellcheck="false">
          {{ transfer_formset.empty_form.from_acc }}
        </td>
        <td class="amount">{{ transfer_formset.empty_form.amount }}</td>
        <td class="to_acc">
          <input type="text" name="to_acc" class="input_to_acc" maxlength="3" autocomplete="off" spellcheck="false">
          {{ transfer_formset.empty_form.to_acc }}
        </td>
        <td class="to_acc_data"></td>
      </tr>`;
      last_row = $("#transfer_formset tr:last")

      // L'id de chaque form ressemble à `form-<id>`
      num_rows = parseInt(last_row.attr("id").split("-")[1]);

      new_row = $(row_template.replace(/__prefix__/g, num_rows + 1))
      last_row.after(new_row)
      // On incrémente le nombre de formsets dans la form globale
      $("#id_form-TOTAL_FORMS").val(function(i, oldval) {
        return ++oldval ;
      });

      return new_row
    }
});
</script>

{% endblock %}
