{% extends "base.html" %}{% block content %}
<script>
  let autoRefreshInterval;
  const protocol = '{{ protocol }}';
  const host = window.location.host;
  const prefix = '{{ prefix }}';
  const baseurl = protocol + '://' + host + prefix;

  function escapeHtml(s) {
    if (s == null) return '';
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
  }

  function showNotification(message) {
    const notification = document.createElement('div');
    notification.className = 'notification';
    notification.textContent = message;
    document.body.appendChild(notification);
    setTimeout(function () { document.body.removeChild(notification); }, 3000);
  }

  function showErrorNotification(message) {
    const notification = document.createElement('div');
    notification.className = 'error-notification';
    notification.textContent = message;
    document.body.appendChild(notification);
    setTimeout(function () { document.body.removeChild(notification); }, 3000);
  }

  function startAutorefresh() {
    clearInterval(autoRefreshInterval);
    autoRefreshInterval = setInterval(function () { if (window.autoRefreshEnabled) updateQueuesData(); }, 5000);
  }

  function stopAutorefresh() {
    clearInterval(autoRefreshInterval);
  }

  document.addEventListener('DOMContentLoaded', function () {
    if (window.autoRefreshEnabled) { startAutorefresh(); }
    updateQueuesData();
  });

  document.addEventListener('autorefresh-changed', function (e) {
    if (e.detail.enabled) {
      startAutorefresh();
      showNotification('Autorefresh enabled');
    } else {
      stopAutorefresh();
      showNotification('Autorefresh disabled');
    }
  });

  function updateQueuesData() {
    fetch(baseurl + '/queues/json')
      .then(function (r) { return r.json(); })
      .then(function (data) { updateQueuesTable(data); })
      .catch(function (error) {
        console.error('Error fetching queues data: ', error);
        showErrorNotification('Error fetching queues data');
      });
  }

  function setBtnLoading(btn) {
    btn.disabled = true;
    btn.classList.add('opacity-50', 'cursor-not-allowed');
    btn.dataset.originalHtml = btn.innerHTML;
    btn.innerHTML = '<svg class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/></svg>';
  }

  function resetBtn(btn) {
    btn.disabled = false;
    btn.classList.remove('opacity-50', 'cursor-not-allowed');
    btn.innerHTML = btn.dataset.originalHtml;
  }

  function deleteJobsInQueue(queue_name, btn) {
    setBtnLoading(btn);
    fetch(baseurl + '/queues/' + queue_name, { method: 'DELETE' })
      .then(function (r) {
        if (!r.ok) { showErrorNotification('Error deleting jobs in queue'); resetBtn(btn); }
        else { updateQueuesData(); }
      })
      .catch(function (error) {
        console.error('Error deleting jobs in queue: ', error);
        showErrorNotification('Error deleting jobs in queue');
        resetBtn(btn);
      });
  }

  function updateQueuesTable(data) {
    var tableBody = document.querySelector('#queues tbody');
    tableBody.innerHTML = '';

    data.forEach(function (queue_stats) {
      var safeQueueName = escapeHtml(queue_stats.queue_name);
      var encodedQueueName = encodeURIComponent(queue_stats.queue_name);
      var states = ['queued', 'started', 'failed', 'deferred', 'finished'];
      var cells = states.map(function (state) {
        return '<td class="td-cell"><a class="text-blue-700 dark:text-blue-400" href="' + baseurl + '/jobs?state=' + state + '&queue_name=' + encodedQueueName + '">' + queue_stats[state] + '</a></td>';
      }).join('');

      tableBody.innerHTML +=
        '<tr class="tr-stripe">' +
        '<td class="td-cell">' + safeQueueName + '</td>' +
        cells +
        '<td class="td-cell"><button class="btn-delete" data-queue="' + safeQueueName + '" title="Delete jobs"><svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2m3 0v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6h14"/></svg></button></td>' +
        '</tr>';
    });

    tableBody.querySelectorAll('[data-queue]').forEach(function (btn) {
      btn.addEventListener('click', function () {
        deleteJobsInQueue(this.getAttribute('data-queue'), this);
      });
    });
  }
</script>

<div class="max-w-[90%] mx-auto mt-6 px-4">
  <table id="queues" class="data-table">
    <thead>
      <tr>
        <th class="th-cell">Queue Name</th>
        <th class="th-cell">Queued</th>
        <th class="th-cell">Started</th>
        <th class="th-cell">Failed</th>
        <th class="th-cell">Deferred</th>
        <th class="th-cell">Finished</th>
        <th class="th-cell">Actions</th>
      </tr>
    </thead>
    <tbody>
      {% for queue_stats in queue_data %}
      <tr class="tr-stripe">
        <td class="td-cell">
          <a class="text-blue-700 dark:text-blue-400" href="{{baseurl}}/jobs?queue={{ queue_stats.queue_name }}">
            {{ queue_stats.queue_name }}
          </a>
        </td>
        <td class="td-cell">
          <a class="text-blue-700 dark:text-blue-400" href="{{baseurl}}/jobs?queue={{ queue_stats.queue_name }}&state=queued">
            {{ queue_stats.queued }}
          </a>
        </td>
        <td class="td-cell">
          <a class="text-blue-700 dark:text-blue-400" href="{{baseurl}}/jobs?queue={{ queue_stats.queue_name }}&state=started">
            {{ queue_stats.started }}
          </a>
        </td>
        <td class="td-cell">
          <a class="text-blue-700 dark:text-blue-400" href="{{baseurl}}/jobs?queue={{ queue_stats.queue_name }}&state=failed">
            {{ queue_stats.failed }}
          </a>
        </td>
        <td class="td-cell">
          <a class="text-blue-700 dark:text-blue-400" href="{{baseurl}}/jobs?queue={{ queue_stats.queue_name }}&state=deferred">
            {{ queue_stats.deferred }}
          </a>
        </td>
        <td class="td-cell">
          <a class="text-blue-700 dark:text-blue-400" href="{{baseurl}}/jobs?queue={{ queue_stats.queue_name }}&state=finished">
            {{ queue_stats.finished }}
          </a>
        </td>
        <td class="td-cell">
          <button class="btn-delete" data-queue-ssr="{{ queue_stats.queue_name }}" title="Delete jobs">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2m3 0v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6h14"/></svg>
          </button>
        </td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('[data-queue-ssr]').forEach(function (btn) {
      btn.addEventListener('click', function () {
        deleteJobsInQueue(this.getAttribute('data-queue-ssr'), this);
      });
    });
  });
</script>
{% endblock %}
