

<div class="container-fluid  dashboard-content">
    <!-- Header -->
    {% set title = "Forms" %}
    {% include 'include_header.html' %}

    <div class="row" style="margin-bottom: 10px">
        <div class="col-12 text-right">
          <a href="javascript:editForm(null)" class="btn btn-primary"><i class="fas fa-plus-circle"></i>  Create Form</a>
        </div>
      </div>

    <div class="row">
        <!-- ============================================================== -->
        <!--  resources table  -->
        <!-- ============================================================== -->
        <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
            <div class="card">
                <h5 class="card-header">Forms List</h5>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table">
                            <thead class="bg-light">
                                <tr class="border-0">
                                    <th class="border-0">Id</th>
                                    <th class="border-0">Name</th>
                                    <th class="border-0">Definition</th>
                                    {% if current_user.is_manager %}
                                    <th class="border-0">Actions</th>
                                    {% endif %}
                                </tr>
                            </thead>
                            <tbody>
                            {% for f in forms %}
                                <tr>
                                    <td id="form_{{ f['id'] }}_id"> {{ f['id'] }} </td>
                                    <td id="form_{{ f['id'] }}_name"> {{ f['name'] }} </td>
                                    <td id="form_{{ f['id'] }}_desc"> {{ f['definition'] }}</td>
                                    {% if current_user.is_manager %}
                                    <td>
                                        <button class="btn btn-sm btn-outline-light" onclick="javascript:showForm({{ f['id'] }})"><i class="fas fa-eye"></i></button>
                                        <button class="btn btn-sm btn-outline-light" onclick="javascript:editForm({{ f['id'] }})"><i class="far fa-edit"></i></button>
                                        <button class="btn btn-sm btn-outline-light" onclick="javascript:deleteForm({{ f['id'] }})"
                                                data-id="{{ f['id'] }}" data-name="{{ f['name'] }}"><i class="far fa-trash-alt"></i></button>
                                    </td>
                                    {% endif %}
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <!-- ============================================================== -->
        <!-- end resources table  -->
        <!-- ============================================================== -->
    </div>
</div>

<!-- ============================================================== -->
<!-- Dynamic Form -->
<!-- ============================================================== -->
<div class="modal" id="show-form-modal" tabindex="-1" role="dialog" aria-labelledby="dynamicModal" aria-hidden="true">

</div>

<!-- ============================================================== -->
<!-- Edit Form -->
<!-- ============================================================== -->
<div class="modal" id="edit-form-modal" tabindex="-1" role="dialog" aria-labelledby="editDynamicModal" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-xl" role="document" data-backdrop="static" data-keyboard="false">
    <div class="modal-content">
      <div class="modal-header">
        <h3 class="modal-title" id="edit-form-modal-title-id"> Form (id=x) </h3>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">

        <div class="row">
            <!-- Application Form -->
            <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                <form id="transaction-form" data-parsley-validate="" novalidate="">
                    <input type="hidden" id="transaction-id" name="transaction-id" value="">

                    <!-- Title Row -->
                    <div class="form-group row">
                        <label class="col-12 col-sm-3 col-form-label text-sm-right">Name</label>
                        <div class="col-12 col-sm-8 col-lg-6">
                            <input type="text" required="" placeholder="Form Name" id="form-name-id" name="form-name"  class="form-control" value="">
                        </div>
                    </div>

                    <!-- Comment Row -->
                    <div class="form-group row">
                        <label class="col-12 col-sm-3 col-form-label text-sm-right">Json Definition</label>
                        <div class="col-12 col-sm-8 col-lg-6">
{#                            <textarea rows="30" required="" placeholder="Form Json" id="form-json-id" name="form-json" class="form-control">#}
{#                            </textarea>#}

                            <div id="editor"></div>
                        </div>
                    </div>

                </form>
            </div>
            <!-- end Application Form -->
        </div>
      </div>

      <div class="modal-footer">

          {% if current_user.is_manager %}
            <button type="button" id="application-btn-cancel"  class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
            <button type="button" id="application-btn-ok" class="btn btn-outline-dark" onclick="javascript: onFormOk()">Update</button>
          {% else %}
              <button type="button" id="application-btn-ok"  class="btn btn-outline-secondary" data-dismiss="modal">OK</button>
          {% endif %}

      </div>
    </div>
  </div>
</div>

<style type="text/css" media="screen">
    #editor {
        position: relative;
        width: 100%;
        height: 400px;
    }
</style>

<script>
    var editor = null;
    var form = null;

    (function(window, document, $, undefined) {
    "use strict";

    $('select').selectpicker();

    editor = ace.edit("editor");
    //editor.renderer.setShowGutter(false);
    editor.setTheme("ace/theme/monokai");
    editor.session.setMode("ace/mode/json");

})(window, document, window.jQuery);
</script>

<script>

/* Show the Application Form, either for a new booking or an existing one */
function showForm(formId) {
    ajaxContent = get_ajax_content("dynamic_form_modal", {form_id: formId});

    ajaxContent.done(function(html) {
        $("#show-form-modal").html(html);
        // Show the form after setting html content
        $('#show-form-modal').modal('show');
    });

    ajaxContent.fail(function(jqXHR, textStatus) {
        alert( "Request failed: " + textStatus );
    });

}  // function showApplication

/* Show the Form, either for updating or creating a new one */
function editForm(formId) {
    if (formId == null) {
        form = {
            id: null,
            name: '',
            definition: {title: "New form", sections: []}
        }
    }
    else {
        var name = "form_" + formId.toString() + "_name";
        var desc = "form_" + formId.toString() + "_desc";
        form = {
            id: formId,
            name: document.getElementById(name).textContent.trim(),
            definition: JSON.parse(document.getElementById(desc).textContent)
        }
    }

    document.getElementById("edit-form-modal-title-id").textContent = "Form (id = " + form.id + ")";
    document.getElementById("form-name-id").value = form.name;
    editor.setValue(JSON.stringify(form.definition, null, 4));

    $('#edit-form-modal').modal('show');


}  // function showApplication

function onFormOk() {
// Update template values
    form.name = document.getElementById("form-name-id").value.trim();
    form.definition = JSON.parse(editor.getValue());

    var endpoint = null;

    if (form.id != null) {
        endpoint = "{{ url_for('api.update_form') }}";
    }
    else {
        endpoint = "{{ url_for('api.create_form') }}";
    }

    var ajaxContent = $.ajax({
        url: endpoint,
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({attrs: form}),
        dataType: "json"
    });

    ajaxContent.done(function(jsonResponse) {
        if ('error' in jsonResponse)
            showError(jsonResponse['error']);
        else
            window.location.reload();
    });

    ajaxContent.fail(function(jqXHR, textStatus) {
        showError( "Request failed: " + textStatus );
    });

}

function deleteForm(form_id) {
    confirm("Delete Session",
            "Do you want to DELETE Form with id=" + form_id + "?",
             "Cancel", "Delete",
            function () {
                    var ajaxContent = $.ajax({
                        url: "{{ url_for('api.delete_form') }}",
                        type: "POST",
                        contentType: 'application/json; charset=utf-8',
                        data: JSON.stringify({attrs: {id: form_id}}),
                        dataType: "json"
                    });

                    ajaxContent.done(function(jsonResponse) {
                        if ('error' in jsonResponse)
                            showError(jsonResponse['error']);
                        else
                            window.location.reload();
                    });

                    ajaxContent.fail(function(jqXHR, textStatus) {
                        showError( "Request failed: " + textStatus );
                    });
            }
            );
} // function deleteSession
</script>

