<h1>Upload queue</h1>
<p class="pagebar">Exactly what the upload stage will do, and what it has already done —
inspect here before any real run.</p>
<div id="queuebody"></div>
<script>
"use strict";

function table(headers, rows) {
  return `<div class="ledger"><table>
    <tr>${headers.map(h => `<th scope="col">${esc(h)}</th>`).join("")}</tr>
    ${rows.join("")}</table></div>`;
}

function render(q) {
  let html = "";

  html += `<h2>To add <span class="count">— ${q.to_add.length} new collection entr${q.to_add.length === 1 ? "y" : "ies"}</span></h2>`;
  html += q.to_add.length
    ? table(["game", "version", "seen in"], q.to_add.map(r => `
        <tr><td class="t">${esc(r.bgg_name)} <span class="meta">· ${esc(r.bgg_id)}</span></td>
        <td>${r.version_name ? esc(r.version_name) : `<span class="meta">no version</span>`}</td>
        <td class="meta">${esc((r.source_photos ?? "").split(";").join(", "))}</td></tr>`))
    : `<p class="empty">Nothing queued — run <b>diff</b> from the <a href="/">pipeline</a> first.</p>`;

  html += `<h2>Version updates <span class="count">— ${q.to_update.length} existing entr${q.to_update.length === 1 ? "y" : "ies"} gaining a version</span></h2>`;
  html += q.to_update.length
    ? table(["game", "version to set", "collection id"], q.to_update.map(r => `
        <tr><td class="t">${esc(r.bgg_name)} <span class="meta">· ${esc(r.bgg_id)}</span></td>
        <td>${esc(r.version_name)}</td>
        <td class="meta">${esc(r.collid)}</td></tr>`))
    : `<p class="empty">No version updates pending.</p>`;

  html += `<h2>Upload log <span class="count">— every attempt ever made (${q.log.length})</span></h2>`;
  html += q.log.length
    ? table(["when", "action", "game", "status", "note"], q.log.slice().reverse().map(r => `
        <tr><td class="meta">${esc(r.timestamp)}</td>
        <td class="meta">${esc(r.action)}</td>
        <td class="t">${esc(r.name)}</td>
        <td>${esc(r.status)}</td>
        <td class="meta">${esc(r.error)}</td></tr>`))
    : `<p class="empty">No uploads attempted yet.</p>`;

  document.getElementById("queuebody").innerHTML = html;
}

let LAST = null;
async function refresh() {
  const q = await fetchJSON("/api/queue");
  const payload = JSON.stringify(q);
  if (payload === LAST) return;
  render(q);
  LAST = payload;  // after render: a throw must not freeze the page as "current"
}

refresh().catch(err => errorBanner(err.message || err));
pollLoop(refresh, 5000, () => showBanner(""));
</script>
