const { fmt, ui, $ } = Admin;

Admin.onStatus((status) => {
  const byType = status.library.byType || {};
  $('library-tiles').innerHTML = ui.tiles([
    ['items', fmt.number(status.library.total), { icon: 'library', tone: 'data' }],
    ...Object.keys(byType).sort().map((type) => [type, fmt.number(byType[type]), { icon: 'list' }]),
    ['last import', fmt.when(status.library.lastSynced), { small: true, icon: 'clock' }],
  ]);

  const running = status.syncRunning;
  $('sync-incremental').disabled = running;
  $('sync-full').disabled = running;
  $('sync-hint').textContent = running
    ? 'Import running…'
    : 'An incremental import runs automatically every ' + status.syncEvery + '.';
});

const sync = (kind) => Admin.api('/admin/api/sync', {
  method: 'POST', body: JSON.stringify({ kind }),
});

Admin.ready(() => {
  $('sync-incremental').addEventListener('click', () => Admin.act(() => sync('incremental')));
  $('sync-full').addEventListener('click', () => {
    if (!confirm('Re-import the entire library? This can take several minutes.')) return;
    Admin.act(() => sync('full'));
  });
});
