{% extends "_base.html" %}
{% import 'tables/_macros.html' as table_macros %}

{% block body %}
<div class="row">
  <div class="col">
    <h2 class="mb-3">SQL Query</h2>

    <form action="{{ request.url.path }}" method="get">
      <div class="mb-3">
        <textarea id="sql-editor" name="sql" rows="5" class="form-control">{{ sql_query }}</textarea>
      </div>

      {% if sql_params|length %}
      <h3 class="mb-3">Parameters</h3>
      {% for param_name, param_value in sql_params.items() %}
      <div class="row mb-3">
        <label for="param-{{ param_name }}" class="col-form-label col-sm-2">{{ param_name }}</label>
        <div class="col-sm-4">
          <input id="param-{{ param_name }}" class="form-control" name="{{ param_name }}" value="{{ param_value }}">
        </div>
      </div>
      {% endfor %}
      {% endif %}

      <div class="mb-3">
        <div class="d-flex justify-content-end">
          <button type="submit" class="btn btn-primary">
            <i class="bi-lightning" aria-hidden="true"></i> Execute
          </button>
        </div>
      </div>
    </form>

    {% if error %}
    <div class="alert alert-danger" role="alert">
      {{ error.message }}
    </div>
    {% else %}
    <div class="d-flex justify-content-between align-items-center mb-2">
      <h3>Results</h3>
      <a href="/tables/query/csv?sql={{ sql_query | urlencode }}" class="btn btn-outline-secondary btn-sm">
        <i class="bi-download" aria-hidden="true"></i> Export CSV
      </a>
    </div>
    <div class="table-responsive">
      <table class="table table-sm table-bordered table-striped table-hover">
        <thead>
          <tr>
            {% for column in table_results.column_names %}
            <th>{{ column }}</th>
            {% endfor %}
          </tr>
        </thead>
        <tbody class="table-group-divider">
          {% for row in table_results.to_pylist() %}
          <tr>
            {% for column in table_results.column_names %}
            <td>{{ row[column] }}</td>
            {% endfor %}
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
    {% endif %}
  </div>
</div>
{% endblock %}

{% block extra_scripts %}
<script src="{{ url_for('static', path='/editor.bundle.js') }}"></script>
<script>
  window.addEventListener("DOMContentLoaded", () => {
    const textArea = document.querySelector("textarea#sql-editor")
    textArea.style.display = "none";
    const sqlSchema = {{ sql_schema | tojson }}
    const sqlEditor = editor.createEditor(textArea, { readOnly: false, dialect: 'duckdb', schema: sqlSchema})
  })
</script>
{% endblock %}