{% extends 'base.html' %}

{% block content %}
<div class="row">
  <div class="col-md-6">
    <div class="card">
      <div class="card-header">
        <h3 class="card-title">{{ form_title }}</h3>
      </div>
      <div class="card-body">
        <div class="form-group">
          <label>Api Endpoint</label>
          <pre class="heighlight">{{ request.host_url }}api/{{ pid }}</pre>
        </div>
        <div class="form-group">
          <label>Api Method</label>
          <pre class="heighlight">POST</pre>
        </div>
        {% for field in form %}
          <div class="form-group {{field.name}} {% if field.errors %}has-error{% endif %}">
            {{ field.label }} {% if field.flags.required %}<span class="text-danger">*</span>{% endif %}
            {{ field(class_="form-control") }}
            {% for message in field.errors %}
              <div class="text-danger">{{ message }}</div>
            {% endfor %}
          </div>
        {% endfor %}
      </div>
      <div class="card-footer">
        <input type="submit" value="{% if btn_name %}{{btn_name}}{% else %}Save{% endif %}" class="btn btn-primary btn-post"/>
      </div>
    </div>
  </div>
  <div class="col-md-6">
    <div class="card">
      <div class="card-header">
        <h3 class="card-title">Api Output</h3>
      </div>
      <div class="card-body">
        <pre class="heighlight" id="api_output">Api output will display here</pre>
      </div>
    </div>
  </div>
</div>
<script type=text/javascript>
  api_endpoint = '{{ request.host_url }}api/{{ pid }}';
  $(function() {
    $('.btn-post').bind('click', function() {
      $('.btn-post').attr('disabled', true);
      $('#api_output').html('<i class="fas fa-sync fa-spin"></i> Please wait...');
      $.post(api_endpoint, $('#input').val()).done(function(data){
        try {
          $('#api_output').text(JSON.stringify(JSON.parse(data), null, 4));
        }
        catch(e) {
          $('#api_output').text(JSON.stringify(data, null, 4));
        }
        $('.btn-post').removeAttr('disabled');
      });
      return false;
    });
  });
</script>
{% endblock %}