{% extends "base.html" %}
<!--              -->
{% load bootstrap3 %}
<!--              -->
{% block title %} Login {% endblock %}
<!--              -->
{% block content %}

<div class="kpx_login">
  <h3 class="kpx_authTitle">Login</h3>
  <div class="row kpx_row-sm-offset-3">
    <div class="col-xs-12 col-sm-6">
      <form class="kpx_loginForm" autocomplete="off" method="POST">
        {% csrf_token %}
        <!--              -->
        {% bootstrap_form form %}
        <input type="hidden" name="next" value="{{ next }}" />
        <hr />
        {% buttons %}
        <button type="submit" class="btn btn-lg btn-outline-primary btn-block">
          <i class="glyphicon glyphicon-log-in" id="btn-submit"></i>
          JWT Login
        </button>
        {% endbuttons %}
      </form>
    </div>
  </div>
</div>

<script>
  const getObjectKeys = (obj, prefix = "") => {
    return Object.entries(obj).reduce((collector, [key, val]) => {
      const newKeys = [...collector, prefix ? `${prefix}.${key}` : key];
      if (Object.prototype.toString.call(val) === "[object Object]") {
        const newPrefix = prefix ? `${prefix}.${key}` : key;
        const otherKeys = getObjectKeys(val, newPrefix);
        return [...newKeys, ...otherKeys];
      }
      return newKeys;
    }, []);
  };

  $("form").on("submit", function (event) {
    event.preventDefault();

    $.ajax({
      type: "POST",
      url: "/{{ jwt_token_url }}",
      data: $(this).serialize(),
      success: function (data) {
        const keys = getObjectKeys(data);
        $.each(keys, function (idx) {
          const key = keys[idx];
          localStorage.setItem(key, data[key]);
        });
        window.location.href = "/{{ dashboard_url }}";
      },
    });
  });
</script>

{% endblock %}
