
<div class="container-fluid dashboard-content">
    <!-- Header -->
    {% set title = "Applications" %}
    {% set navigation = [('Admin', ''), ('Applications', '')] %}
    {% include 'include_header.html' %}

    <div class="row">
    <!-- ============================================================== -->
        <!-- Create new Applications  -->
        <!-- ============================================================== -->
        <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12 mb-5">
            <div class="tab-regular">
                <div class="row">
                    <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                        <div class="section-block" id="cards">
                            <h3 class="section-title">Create a New Application</h3>
                        </div>
                    </div>
                    {% for t in templates %}
                        {% if t.status == 'active' %}
                         <div class="col-xl-3 col-lg-3 col-md-3 col-sm-6 col-6">
                            <div class="card">
                                <div class="card-body">
                                    <h4 class="card-title border-bottom pb-2">{{ t.title }}</h4>
                                    <p class="card-text"> {{ t.description }}</p>
                                    <a href="#" class="btn btn-primary"><i class="fas fa-plus-circle"></i> Create Application</a>
                                </div>
                            </div>
                        </div>
                        {% endif %}
                    {% endfor %}
                </div>
            </div>
        </div>
        <!-- ============================================================== -->
        <!-- end - Create New Applications  -->
        <!-- ============================================================== -->

        <!-- ============================================================== -->
        <!-- Application Tabs  -->
        <!-- ============================================================== -->
        <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12 mb-5">
            <div class="row">
                <div class="col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3">
                    <div class="section-block" id="applications">
                        <h3 class="section-title">Applications</h3>
                    </div>
                </div>
            </div>
            <div class="tab-vertical">
                <ul class="nav nav-tabs " id="applicationTabsNav" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link" id="preparation-tab" data-toggle="tab" href="#preparation" role="tab" aria-controls="preparation" aria-selected="false">Preparation</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="submitted-tab" data-toggle="tab" href="#submitted" role="tab" aria-controls="submitted" aria-selected="false">Review</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" id="active-tab" data-toggle="tab" href="#active" role="tab" aria-controls="active" aria-selected="true">Active</a>
                    </li>
                </ul>
                <div class="tab-content" id="applicationTabsContent">
                    <div class="tab-pane fade" id="preparation" role="tabpanel" aria-labelledby="preparation-tab">
                        {% set status = ["preparation"] %}
                        {%  include "include_applications_table.html" %}
                    </div>
                    <div class="tab-pane fade" id="submitted" role="tabpanel" aria-labelledby="submitted-tab">
                        {% set status = ["review", "accepted", "rejected"] %}
                        {%  include "include_applications_table.html" %}
                    </div>
                    <div class="tab-pane fade show active" id="active" role="tabpanel" aria-labelledby="active-tab">
                        {% set status = ["active"] %}
                        {%  include "include_applications_table.html" %}
                    </div>

                </div>
            </div>
        </div>
        <!-- ============================================================== -->
        <!-- end - Application Tabs  -->
        <!-- ============================================================== -->


    </div>  <!-- row -->

    <div>
        <!-- ============================================================== -->
        <!-- Template Tabs  -->
        <!-- ============================================================== -->
        <div class="row">
            <div class="col-xl-3 col-lg-3 col-md-3 col-sm-3 col-3">
                <div class="section-block" id="templates">
                    <h3 class="section-title">Templates</h3>
                </div>
            </div>
            <div class="col-xl-9 col-lg-9 col-md-9 col-sm-9 col-9  text-sm-right">
                <a href="javascript:showTemplate()" class="btn btn-primary"><i class="fas fa-plus-circle"></i>  Create Template</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12 mb-5">
                <div class="tab-vertical">
                    <ul class="nav nav-tabs " id="templateTabsNav" role="tablist">
                    {%  for status in template_statuses %}
                        {% set active_str = "active" if status == template_selected_status else "" %}
                        {% set active_selected = "true" if status == template_selected_status else "false" %}
                        <li class="nav-item">
                            <a class="nav-link {{ active_str }}" id="{{ status }}-t-tab" data-toggle="tab" href="#{{ status }}-t" role="tab" aria-controls="{{ status }}-t" aria-selected="{{ active_selected }}">{{ status }}</a>
                        </li>
                    {%  endfor %}
                    </ul>
                    <div class="tab-content" id="templateTabsContent">
                    {%  for status in template_statuses %}
                        {% set active_str = "show active" if status == template_selected_status else "" %}
                        <div class="tab-pane fade {{ active_str }}" id="{{ status }}-t" role="tabpanel" aria-labelledby="{{ status }}-t-tab">
                            {% include 'include_templates_table.html' %}
                        </div>
                    {%  endfor %}
                    </div>
                </div>
            </div>
        </div>
        <!-- ============================================================== -->
        <!-- end - Template Tabs  -->
        <!-- ============================================================== -->
    </div>



</div>

<!-- ============================================================== -->
<!-- Template Modal -->
<!-- ============================================================== -->
<div class="modal fade" id="template-modal" tabindex="-1" role="dialog" aria-labelledby="templateModal" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h3 class="modal-title" id="template-modal-title"> TITLE </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">

            <!-- Template Form -->
            <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                <form id="validationform" data-parsley-validate="" novalidate="">

                    <!-- Title Row -->
                    <div class="form-group row">
                        <label class="col-12 col-sm-3 col-form-label text-sm-right">Title</label>
                        <div class="col-12 col-sm-8 col-lg-6">
                            <input type="text" required="" placeholder="Type something" id="template-title" class="form-control">
                        </div>
                    </div>

                    <div class="form-group row">
                        <label class="col-12 col-sm-3 col-form-label text-sm-right">Description </label>
                        <div class="col-12 col-sm-8 col-lg-6">
                            <textarea required="" class="form-control" id="template-description"></textarea>
                        </div>
                    </div>

                    <!-- Template Status -->
                   <div class="form-group row">
                        <label class="col-sm-3 col-form-label text-sm-right">Template Status</label>
                        <div class="col-sm-6">
                            <select class="selectpicker show-tick" data-width="auto" id="template-status-select">
                              <option value="preparation">Preparation</option>
                              <option value="active">Active</option>
                              <option value="closed">Closed</option>
                            </select>
                        </div>
                    </div>

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

      <div class="modal-footer">
        <button type="button" id="template-btn-cancel"  class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
        <button type="button" id="template-btn-ok" class="btn btn-outline-dark" onclick="javascript: onTemplateOkButtonClick()">Update</button>
      </div>
    </div>
  </div>
</div>
<!-- ============================================================== -->
<!-- End of Template Modal -->
<!-- ============================================================== -->


<!-- ============================================================== -->
<!-- Application Modal -->
<!-- ============================================================== -->
<div class="modal fade" id="application-modal" tabindex="-1" role="dialog" aria-labelledby="applicationModal" aria-hidden="true">
</div>

<!-- ============================================================== -->
<!-- End of Application Modal -->
<!-- ============================================================== -->


<script>
  $('#deleteModal').on('show.bs.modal', function (event) {
      var button = $(event.relatedTarget); // Button that triggered the modal

      // Extract info from data-* attributes
      var id = button.data('id')
      var name = button.data('name')

      // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
      // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
      var modal = $(this)
      // modal.find('.modal-title').text('New message to ' + recipient)
      modal.find('.modal-body').html('<p> Do you want to DELETE user <b>' + name + '</b> (id = ' + id + ') ? </p>')
    })
</script>


<script>
    var applications;
    var applicationDict = {};
    var templates;
    var templateDict = {};
    var template = null;


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

    $('select').selectpicker();

    templates = {{ templates|tojson }};
    for (var t of templates)
        templateDict[t.id] = t;

})(window, document, window.jQuery);


/* Show the Template Form, either for a new booking or an existing one */
function showTemplate(templateId) {
    if (templateId == null)
        template = {
            id: null,
            status: 'preparation'
        };
    else
        // Get the template with that id
        template = templateDict[templateId];

    if (template == null) {
        showMessage("ERROR", "Invalid Template id: " + templateId);
        return
    }

    // Setup fields with template values
    $('#template-title').val(template.title);
    $('#template-description').val(template.description);

    // Set possible status options depending on the current status
    $('#template-status-select').selectpicker('val', template.status);
    $('#template-status-select').find("[value='closed']").prop('disabled', false);
    $('#template-status-select').find("[value='preparation']").prop('disabled', false);

    if (template.status == 'preparation')
        $('#template-status-select').find("[value='closed']").prop('disabled', true);
    else
        $('#template-status-select').find("[value='preparation']").prop('disabled', true);

    $('#template-status-select').selectpicker('refresh');

    // Show the form
    $('#template-modal').modal('show');
}  // function showTemplate


/* Show the Application Form, either for a new booking or an existing one */
function showApplication(applicationId) {
    ajaxContent = get_ajax_content("application_form", {application_id: applicationId});

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

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

}  // function showApplication

/** Helper functions to handle Template AJAX response or failure */
function handleAjaxDone(jsonResponse) {
    var error = null;

    if ('template' in jsonResponse) {
    }
    else if ('error' in jsonResponse) {
        error = jsonResponse.error;
    }
    else {
        error = 'Unexpected response from server.'
    }

    if (error)
        showMessage('ERROR', error);
    else {
        $('#template-modal').on('hidden.bs.modal', function () {
            var params = {template_selected_status: template.status}
            load_main_content("applications", params);
        });
        $('#template-modal').modal('hide');
    }
}


function handleAjaxFail(jqXHR, textStatus) {
    showMessage("ERROR", "Request failed: " + textStatus );
}


/** This function will be called when the OK button in the Template form
 * is clicked. It can be either Create or Update action.
 */
function onTemplateOkButtonClick() {
    // Update template values
    template.title = $('#template-title').val();
    template.description = $('#template-description').val();
    template.status = $('#template-status-select').selectpicker('val');

    if (template.id) {
        endpoint = "{{ url_for('api.update_template') }}";
    }
    else {
        endpoint = "{{ url_for('api.create_template') }}"
    }

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

    ajaxContent.done(handleAjaxDone);
    ajaxContent.fail(handleAjaxFail);
}  // function onTemplateOkButtonClick

/** Helper functions to handle Application AJAX response or failure */
function handleApplicationAjaxDone(jsonResponse) {
    var error = null;
    console.log("type: ", typeof(jsonResponse));

    if ('application' in jsonResponse) {
    }
    else if ('error' in jsonResponse) {
        error = jsonResponse.error;
    }
    else {
        error = 'Unexpected response from server.'
    }

    if (error)
        showMessage('ERROR', error);
    else {
        $('#application-modal').on('hidden.bs.modal', function () {
            var params = {}
            load_main_content("applications", params);
        });
        $('#application-modal').modal('hide');
    }
}

/** This function will be called when the OK button in the Application form
 * is clicked. It can be either Create or Update action.
 */
function onApplicationOkButtonClick() {
    // Update template values
    var application = {
        id: parseInt($('#application-id').val()),
        title: $('#application-title').val(),
        alias: $('#application-alias').val(),
        description: $('#application-description').val(),
        resource_allocation: {
            quota: {
                krios: parseInt($('#quota-krios').val()),
                talos: parseInt($('#quota-talos').val())
            },
            noslot: []  // FIXME: Create the proper list
        }
    };

    $( ".noslot" ).each( function( i, el ) {
        var elem = $( el );
        if (elem.prop("checked"))
            application.resource_allocation.noslot.push(parseInt(elem.val()));
        //alert("checked: " + elem.prop('checked') + " value: " + elem.val());
    });

    var endpoint = null;

    if (application.id != null) {
        endpoint = "{{ url_for('api.update_application') }}";
    }
    else {
        endpoint = "{{ url_for('api.create_application') }}";
    }

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

    ajaxContent.done(handleApplicationAjaxDone);
    ajaxContent.fail(handleAjaxFail);
}  // function onTemplateOkButtonClick

</script>