{% extends "admin/base_site_grid.html" %}
{% load i18n %}

{% block extrahead %}{{block.super}}

<script>

{% if perms.reportmanager.change_sqlreport or perms.reportmanager.add_sqlreport %}
function getSchema() {
   $.ajax({
      url: url_prefix + "/reportmanager/schema/",
      type: 'GET',
      datatype: "html",
      success: function(data) {
        $("#schemacolumn").html(data);
        $("#schemacolumn .schema-header").click(function() {
          $(this).children("span.fa").toggleClass("fa-plus").toggleClass("fa-minus");
          $(this).next(".collapse").collapse("toggle");
        });
        $("a.schemafield").on("click", function(e) {
          var field = $(e.target).closest("a").find("code").first().text();
          if (field != "") {
            var statements = $("#reportmanager_statements");
            if (statements[0].selectionStart || statements[0].selectionStart === 0) {
              var startPos = statements[0].selectionStart;
              var endPos = statements[0].selectionEnd;
              statements[0].value = statements[0].value.substring(0, startPos) +
                field + ", " +
                statements[0].value.substring(endPos, statements[0].value.length);
              statements[0].selectionStart = startPos + field.length + 2;
              statements[0].selectionEnd = startPos + field.length + 2;
            }
          else
            this.value += field + ", ";
          }
        });
      },
      async: true
      });
}

function startEdit() {
  $("#editreport, #editbuttons, #filterform").toggleClass("d-none");
  if ($("#schemacolumn").is(":empty")) getSchema();
}
{% endif %}

var xhr;

$(function() {

  $("#reportmanager_statements").resizable({
    handleSelector: "#resize-handle",
    resizeWidth: false,
    resizeHeight: true,
    onDrag: function(e) {
      $("#schemacolumn").height($("#reportmanager_statements").height());
    }
  });

  $("#reportmanager_statements").on("input", function() {
    $("#reportmanager_save").removeClass("btn-primary").addClass("btn-danger");
    $(window).on('beforeunload', function() {
      if ($("#reportmanager_save").hasClass("btn-danger"))
        return 'There are unsaved changes.';
    });
  });

  var id = {% if report %}{{report.id}}{% else %}0{% endif %};

  $("#reportmanager_save").on("click", function(event) {
    var data = {
        "sql": $("#reportmanager_statements").val(),
        "save": true,
        "name": $("#id_name").val(),
        "public": $("#id_public").is(":checked"),
        "description": $("#id_description").val()
        };
    if (id) data["id"] = id;
    xhr = $.ajax({
      url: url_prefix + "/reportmanager/",
      type: 'POST',
      dataType: 'json',
      data: data,
      async: true,
      success: function(data) {
      	if (data.status == "ok") {
          $("#reportmanager_save").addClass("btn-primary").removeClass("btn-danger");
          window.location.href = url_prefix + "/reportmanager/" + data.id + '/';
        }
      	else {
          $("#save_ok").remove();
          $("#workarea").prepend(
            '<div id="save_ok" class="row"><div class="col mt-2">'
            + '<div class="alert alert-danger">{% trans "Saving the report failed" %}&nbsp;:&nbsp;'
            + data.status
            + '</div></div>'
            );
      	}
      }
      });
  });

  $("#reportmanager_format").on("click", function(event) {
    var sql = $("#reportmanager_statements");
    var data = sql.val();
    xhr = $.ajax({
      url: url_prefix + "/reportmanager/",
      type: 'POST',
      dataType: 'json',
      data: {
        "sql": data,
        "format": true
        },
      success: function(data) {
        sql.val(data['formatted']);
      },
      async: true
      });
  });

  {% if report %}
  $("#reportmanager_delete").on("click", function(event) {
    xhr = $.ajax({
      url: url_prefix + "/reportmanager/",
      type: 'POST',
      data: {
        "id": {{report.id}},
        "delete": true
        },
      success: function(data) {
        if (data == "ok") {
          window.location.href = url_prefix + "/data/reportmanager/sqlreport/";
        }
        else {
          $("#workarea").prepend(
            '<div class="alert alert-danger">{% trans "Deleting the report failed" %}&nbsp;:&nbsp;'
            + data.status
            + '</div></div>'
            );
        }
      },
      async: true
      });
  });
  {% endif %}

  $("#reportmanager_cancel").on("click", function(event) {
    if (xhr) {
      xhr.abort();
      xhr = null;
      }
  });

  {% if not report %}
  getSchema();
  {% endif %}
});
</script>
{% endblock %}

{% block actions %}{{block.super}}
{% if perms.reportmanager.change_sqlreport or perms.reportmanager.add_sqlreport %}
<button class="btn btn-sm btn-primary" onclick="startEdit()" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'edit'|capfirst|force_escape %}" ><span class="fa fa-pencil"></span></button>
{% endif %}
{% endblock %}

{% block filter %}{% if report %}{{block.super}}{% endif %}{% endblock %}

{% block before_table %}

<div class="row form-group mb-0">

{% if perms.reportmanager.change_sqlreport %}
<div id="editbuttons" class="col-md-5{% if report %} d-none{% endif %}">
<button id="reportmanager_save" class="btn btn-primary">{% trans "save"|capfirst %}</button>
<button id="reportmanager_format" class="btn btn-primary">{% trans "format SQL query"|capfirst %}</button>
{% if report %}<button id="reportmanager_delete" class="btn btn-primary">{% trans "Delete" %}</button>{% endif %}
</div>
{% endif %}
</div>

<div id="editreport" {% if report %}class="d-none"{% endif %}>
<div class="row pt-2 pb-2">
<div class="col-form-label col-md-2" style="text-align:right">
  <label class="required" style="font-weight:bold; color:#333" for="id_name">{% trans "name"|capfirst %}:</label>
</div>
<div class="controls col-md-10">
  <input type="text" name="name" class="form-control vTextField" maxlength="300"
    placeholder="{% trans "name"|capfirst %}" value="{{report.name}}" required id="id_name">
</div>
</div>

<div class="row pt-2 pb-2">
<div class="col-form-label col-md-2" style="text-align:right">
  <label for="id_description">{% trans "description"|capfirst %}:</label>
</div>
<div class="controls col-md-10">
  <input type="text" name="description" class="form-control vTextField" maxlength="500"
    placeholder="{% trans "description"|capfirst %}" id="id_description"
    {% if report.description %}value="{{report.description}}"{% endif %}>
</div>
</div>

<div class="row pt-2 pb-2">
<div class="form-check-label col-md-2" style="text-align:right">
  <label for="id_public">{% trans "public"|capfirst %}:</label>
</div>
<div class="controls col-md-10">
  <input class="form-check-input" type="checkbox" style="transform: scale(1.5)" name="public" {% if report.public %}checked {% endif %}id="id_public">
  {% if report.public and request.user.id != report.user.id %}&nbsp;&nbsp;&nbsp;{% trans "owned by" %} {{report.user.username}}{% endif %}
</div>
</div>

<div class="row" style="text-align:center">
<div class="col-md-12">
<div id="sqlandschema" style="width:100%">
<table style="table-layout: fixed; width: 100%">
<tr>
<td style="padding-right: 5px">
<h5 style="text-align: left">{% trans "SQL query"|capfirst %}</h5>
<textarea id="reportmanager_statements" rows="10" class="form-control w-100"
 style="height:{% if request.prefs.height %}{{ request.prefs.height}}{% else %}200{% endif %}px; resize: none; font-size:1.25em; font-family:courier">
{{ report.sql }}
</textarea>
</td>
<td style="width:28em; padding-left:5px; padding-right:10px">
<h5>{% trans "schema"|capfirst %}</h5>
<div id="schemacolumn" style="overflow-y: scroll; height:{% if request.prefs.height %}{{ request.prefs.height}}{% else %}200{% endif %}px"></div>
</td>
</tr></table>
</div>
<span id="resize-handle" class="fa fa-bars handle" style="display: inline-block; touch-action: none"></span>
</div>
</div>

<!-- End editing section -->
</div>

{% endblock %}
