{% extends "base.html" %}

{% block extra_head %}
<script src="{{ urls.static_plugins("datasette_alerts", "alerts/index.min.js") }}"></script>
<link   href="{{ urls.static_plugins("datasette_alerts", "alerts/index.min.css") }}" rel="stylesheet" />
<link rel=stylesheet href=https://unpkg.com/missing.css@1.2.0>
<meta name=color-scheme content=light>

<style>
  input:not([type]), input[type="text"], input[type="search"], input[type="tel"], input[type="url"], input[type="email"], input[type="password"], input[type="date"], input[type="month"], input[type="week"], input[type="time"], input[type="datetime"], input[type="datetime-local"], input[type="number"], select, textarea {
  &::placeholder {
    color: var(--muted-fg);
    opacity: 1;
    text-align: start;
  }
}
</style>
{% endblock %}



{% block content %}

<div id="root"></div>


<script>
  async function main() {

    const params = new URLSearchParams(window.location.search);
    if(params.has("db_name") && params.has("table_name")) {
      document.querySelector('input[name="_database"]').value = params.get("db_name");
      document.querySelector('input[name="_table_name"]').value = params.get("table_name");
      const sql = "select * from pragma_table_xinfo(:table)"
      const columns = await fetch(`/${params.get("db_name")}/-/query.json?sql=${sql}&table=${params.get("table_name")}&_shape=array`).then( r => r.json());
      document.querySelector('input[name="_id_column"]').value = columns.filter(c=>c.pk).map(c=>c.name).join(',');
      const tsColumn = columns.find(d=>d.name.endsWith("_at") || d.name.endsWith("_date") || d.name.endsWith("timestamp") || d.name.endsWith("time"));
      if(tsColumn) {
        document.querySelector('input[name="_timestamp_column"]').value = tsColumn.name;
      }
      else if(columns.length == 1) {
        document.querySelector('input[name="_timestamp_column"]').value = columns[0].name;
      }
    }

    document.querySelectorAll('.da-notifier-form').forEach((form) => {
      form.style.display = 'none';
    });

    function show(formSlug) {
        document.querySelectorAll('.da-notifier-form').forEach((form) => {
          form.style.display = 'none';
        });
        const selectedForm = document.getElementById(`datasette-alerts-notifier-${formSlug}`);
        if (selectedForm) {
          selectedForm.style.display = 'block';
        }
    }

    document.querySelectorAll('.x').forEach((x) => {
      x.addEventListener('change', (event) => {
        const formSlug = event.target.value;
        show(formSlug);
      });
    });
    show(document.querySelector('.x:checked').value);

      document.getElementById('myForm').addEventListener('submit', async function(event) {
        event.preventDefault();
        const formData = new FormData(this);
        
        const notifier_slug = formData.get('form');
        
        const notifierMeta = {};
        formData.forEach((value, key) => {
          if(key.startsWith(`${notifier_slug}-`)) {
            notifierMeta[key.slice(`${notifier_slug}-`.length)] = value;
          } 
        });


        
        const body = {
          database_name: formData.get('_database'),
          table_name: formData.get('_table_name'),
          id_columns: [formData.get('_id_column')],
          timestamp_column: formData.get('_timestamp_column'),
          frequency: formData.get('_frequency'),
          subscriptions: [{
            notifier_slug,
            meta:  notifierMeta,
          }]
        };
        console.log(data);
        console.log(body);
        fetch(`/-/datasette-alerts/api/new-alert`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': formData.get('csrftoken'),
          },
          body: JSON.stringify(body),
        })
      });


  }
  const data = {{ data | tojson }};
  window.data = data;
  document.addEventListener("DOMContentLoaded", main);

</script>
<div style="max-width: 800px; margin: auto; padding: 1em;">
<h2>Create Alert</h2>
<form class="table rows" id="myForm">

    <p><label for="_name">Name</label><input type="text" name="_name" placeholder="Alert Name" required/></p>
    <p><label for="_database">Database</label><input type="text" name="_database" placeholder="Database" required/></p>
    <p><label for="_slug">Slug</label><input type="text" name="_slug" placeholder="Slug" required/></p>
    <p><label for="_id_column">ID Columns</label><input type="text" name="_id_column" placeholder="ID Columns" required/></p>
    <p><label for="_table_name">Table name</label><input type="text" name="_table_name" placeholder="Table name" required/></p>
    <p><label for="_timestamp_column">Timestamp column</label><input type="text" name="_timestamp_column" placeholder="Timestamp column" required/></p>
    <p><label for="_frequency">Frequency</label><input type="text" name="_frequency" placeholder="Frequency" required/></p>
  </div>


  <fieldset>
  <legend>Color</legend>
  <ul>
      {% for form in forms %}
      <li>
        <label>
          <input class="x" type="radio" name="form" value="{{ form.slug }}" {% if loop.first %}checked{% endif %}>
          {{form.name}} {{form.icon | safe }}
        </label>
    {% endfor %}
  </ul>
</fieldset>


  {% for form in forms %}
    <div class="da-notifier-form" id="datasette-alerts-notifier-{{form.slug}}">
    {% for field in form.html %}
        <div class="label{% if field.errors %} errors{% endif %}">
          {{ field.label }}
        </div>
        <div class="field{% if field.errors %} errors{% endif %}">
          {{ field }}
          {% if field.errors %}
            <ul class="errors">
              {% for error in field.errors %}
                <li>{{ error }}</li>
              {% endfor %}
            </ul>
          {% endif %}
          {% if field.description %}
            <p style="font-size: 0.8em">{{ field.description }}</p>
          {% endif %}
        </div>
      {% endfor %}
    </div>
  {% endfor %}

  <p>
    <input type="hidden" name="csrftoken" value="{{ csrftoken() }}">
    <input type="submit" value="Create Alert">
  </p>
</form>
</div>
{% endblock %}