{% extends 'base_query.html' %}

{% block content %}
<style>
    .myblock {
        height: 500px;
        width: 30%;
        margin-left:10px;
        border-radius: 5px;
        display:inline-block;
        padding: 5px;
    }
    .blockheader {
        height: 50px;
    }
    .hint {
        color: grey;
        font-size: 70%;
    }
</style>
<div style="">
    <div class="myblock">
        <div class="blockheader">
            <a href=".">Djaq</a>
            <a href="https://djaq.readthedocs.io/" style="font-size: 80%"> (documentation)</a>
                {% comment %} <div style="float:right">
                    <a class="delete is-medium" href="javascript:void(0);" onclick="$('#query').val('');">clear</a>
                    {% endcomment %}
        </div> 
        
        <label for="model">Model name</label>
        <input id="model" placeholder="model name" class="input" />
        <textarea
            placeholder="Fields for output"
            id="output"
            class="textarea"
            style="width:100%;height:20%;"
        ></textarea>
        <span class="hint">Comma separated list of field expressions. Leave blank for all.</span>
        <textarea
            placeholder="Filter expression"
            id="where"
            class="textarea"
            style="width:100%;height:20%;"
        ></textarea>
        <span class="hint">An expression to filter by or blank for no filter.</span>
        <textarea
            placeholder="Order by these fields"
            id="order_by"
            class="textarea"
            style="width:100%;height:20%;"
        ></textarea>
        <span class="hint">Comma separated list of field expressions to sort by or leave blank. Use minus, '-', to sort descending.</span>
    </div>
    <div class="myblock">
        <div class="blockheader">
            <div class="control">
                <div class="select">
                    <select id="app" onchange="get_models()">
                        <option value="">Choose app</option>
                        {% for app in apps %}
                        <option value="{{app}}">{{app}}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="hint" style="float:right">
                    dbl-click model to insert query
                </div>
            </div>
        </div>
        <div id="models" style="overflow:auto;border: 2px solid lightgrey;height:90%">
            <ul id="model_list"></ul>
        </div>
    </div>
    <div class="myblock">
        <div class="blockheader">
            <span id="model-name"></span>
        </div>
        <div id="fields" style="overflow:auto;border: 2px solid lightgrey;height:90%">
            <ul id="field_list"></ul>
        </div>
    </div>
</div>
<div>
    <div class="">
        <div style="display:block">
            <label class="label">Limit/Offset</label>
        </div>
        <div class="field" style="width:80px;display:inline-block">
            <p class="control">
                <input
                    class="input"
                    type="number"
                    placeholder="0"
                    value="100"
                    id="limit"
                >
            </p>
        </div>
        <div class="field" style="width:80px;display:inline-block">
            <p class="control">
                <input
                    class="input"
                    type="number"
                    placeholder="0"
                    value="0"
                    id="offset"
                >
            </p>
        </div>
    </div>
</div>
<div>
    <div>
        <div class="field is-grouped">
            <p class="control">
                <a class="button is-primary is-light" title="Send query and retrieve results (Shift-Enter)" onclick="execute_query();">
                    Send
                </a>
            </p>
            <p class="control">
                <a class="button is-info is-light" title="Represent query as json" onclick="represent_query();">
                    JSON
                </a>
            </p>
            <p class="control">
                <a class="button is-info is-light" title="Get SQL for query" onclick="get_sql();">
                    SQL
                </a>
            </p>
            <p class="control">
                <a class="button is-info is-light" title="Get schema for models" onclick="get_schema();">
                    Schema
                </a>
            </p>
            <p class="control">
                <a class="button is-info is-light" title="Get active whitelist" onclick="get_whitelist();">
                    Whitelist
                </a>
            </p>
        </div>
    </div>
</div>
<textarea class="textarea" id="result" style="width:50%;min-height:500px;margin-top:10px;"></textarea>
<script>
function render_query() {
    var model = $("#model").val();
    var output = $("#output").val();
    var where = $("#where").val();
    var order_by = $("#order_by").val();
    var limit = $("#limit").val();
    var offset = $("#offset").val();

    {% comment %} q =  q.replace(/(\r\n|\n|\r)/gm,""); {% endcomment %}
    query = {
        model: model,
        output: output,
        where: where,
        order_by: order_by,
        limit: limit,
        offset: offset
    }
    return {
        queries: [
            query
        ]
    }
  }

  function represent_query() {
      const s = JSON.stringify(render_query(), null, 1);
      $("#result").val(s);
  }

  function execute_query() {
      $("#result").val('working on it...');
      var url = "/djaq/api/request/"
      $.ajax({
        type: "POST",
        data: JSON.stringify(render_query()),
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            $("#result").val(JSON.stringify(response.result, null, 1));
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $("#result").val(xhr.responseText);
        }
      });
  }
  function get_sql() {
      $("#result").val('working on it...');
      var url = "/dquery/sql/"
      $.ajax({
        type: "POST",
        data: JSON.stringify(render_query()),
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            $("#result").val(response.result);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $("#result").val(xhr.responseText);
        }
      });
  }
  function get_schema() {
      $("#result").val('working on it...');
      var url = "/djaq/api/schema/"
      $.ajax({
          type: "GET",
          url: url,
          success: function(response) {
	      $("#result").val(JSON.stringify(response, null, 1));
          },
          error: function (xhr, ajaxOptions, thrownError) {
              $("#result").val(xhr.responseText);
          }
      });
  }

  function get_models() {
      var appname = $("#app").val();
      var url = `/dquery/models/${appname}/`
      $.ajax({
          type: "GET",
          url: url,
          success: function(response) {
	      $("#model_list").html("");
	      response.models.forEach(function(element) {
		  $("#model_list").append(`<li><a href="javascript:void(0);" onclick="get_fields('${element}')">${element}</a></li>`);
	      });
          },
          error: function (xhr, ajaxOptions, thrownError) {
              $("#result").val(xhr.responseText);
          }
      });
  }

  function get_fields(modelname) {

      var url = `/dquery/fields/${modelname}/`
      $.ajax({
          type: "GET",
          url: url,
          success: function(response) {
            $("#result").val(JSON.stringify(response, null, 1));
            $("#field_list").html("");
            for (let [name, f] of Object.entries(response.fields)) {
                $("#field_list").append(`<li><a href="javascript:void(0);" ">${name}: ${f.internal_type}</a></li>`);
            }
            $("#model-name").html(`${modelname}`)
            $("#model").val(`${modelname}`)
          },
          error: function (xhr, ajaxOptions, thrownError) {
              $("#result").val(xhr.responseText);
          }
      });
  }

  function get_whitelist() {
      var url = `/dquery/whitelist/`
      $.ajax({
          type: "GET",
          url: url,
          success: function(response) {
	      $("#result").val(JSON.stringify(response, null, 1));
          },
          error: function (xhr, ajaxOptions, thrownError) {
              $("#result").val(xhr.responseText);
          }
      });
  }

  function handleEnter(evt) {
      if (evt.keyCode == 13 && evt.shiftKey) {
	  	execute_query(false);
        evt.preventDefault();
    }
}

$( document ).ready(function() {

    $(document).on('dblclick', 'ul li', function(){

	var t = $(this).text();
	console.log($(this).text());

	var parts = t.split(".");
	
	var model_name = parts[parts.length -1]
	var m = model_name.charAt().toLowerCase();
	var fields = '';
	$('ul#field_list li').each(function(i) {
	    var f = $(this).text().split(":")[0];
	    fields += `${f},\n`;
	});
	var $txt = jQuery("#output");
        var caretPos = $txt[0].selectionStart;
        var textAreaTxt = $txt.val();
        $txt.val(textAreaTxt.substring(0, caretPos) + `${fields}` + textAreaTxt.substring(caretPos) );
    });

    $("#output").keydown(handleEnter).keypress(handleEnter);

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