const { fmt, ui, $ } = Admin;

Admin.onStatus((status) => {
  $('request-services').innerHTML =
    ui.tag('Radarr ' + (status.radarrReady ? 'ready' : 'not configured'),
      status.radarrReady ? 'ok' : 'bad') +
    ui.tag('Sonarr ' + (status.sonarrReady ? 'ready' : 'not configured'),
      status.sonarrReady ? 'ok' : 'bad');

  const box = $('request-users');
  if (!Admin.settled(box)) return;
  const allowed = new Set((status.requestPolicy || {}).allowedUserIds || []);
  box.innerHTML = (status.requestUsers || []).length
    ? status.requestUsers.map((user) =>
      '<label class="check"><input type="checkbox" data-request-user="' + fmt.escape(user.id) + '"' +
      (allowed.has(user.id) ? ' checked' : '') + '><span>' + fmt.escape(user.username) +
      '<em>last seen ' + fmt.escape(fmt.when(user.lastSeen)) + '</em></span></label>').join('')
    : ui.empty('No one has signed in yet.');
});

Admin.ready(() => {
  $('request-save').addEventListener('click', () => {
    const allowedUserIds = [...document.querySelectorAll('[data-request-user]:checked')]
      .map((box) => box.dataset.requestUser);
    Admin.act(() => Admin.api('/admin/api/request-policy', {
      method: 'POST', body: JSON.stringify({ allowedUserIds }),
    }));
  });
});
