{% extends "base.html" %}

{% block content %}

  <div class="row">
  <h3>Retrieve User Details</h3><hr/>
    <div class="form-group">
      <label for="token" class="col-sm-2 control-label">User Token</label>
      <div class="col-sm-4">
        <input name="token" type="text" class="form-control" id="token" placeholder="Token">
        <p class="help-block">Token received after login</p>
      </div>
      <button id="get-user-details" class="btn btn-primary">GET user details</button>
    </div>
  </div>

  <div class="row">
    <h3>Update User Details</h3><hr/>
    {% include "fragments/user_details_form.html" %}
  </div>
{% endblock %}

{% block script %}
    <script type="text/javascript">
      $().ready(function(){
        $('#get-user-details').click(function(){
          var token = $('input[name=token]').val();

          $.ajax({
            url: "{% url 'rest_user_details' %}",
            beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Token '+token);},
            type: "GET",
            success: function(data) {
              $('input[name=username]').val(data.username);
              $('input[name=email]').val(data.email);
              $('input[name=first_name]').val(data.first_name);
              $('input[name=last_name]').val(data.last_name);
            }
          });
          return false;
        });

        $('form button[type=submit]').click(function(){
          var token = $('input[name=token]').val();
          var form = $('form');
          $.ajax({
            url: form.attr('action'),
            data: $('form').serialize(),
            type: "PUT",
            beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Token '+token);}
          }).fail(function(data){error_response(data);})
          .done(function(data){susccess_response(data);});
          return false;
        });

      });
    </script>
{% endblock %}
