const { ui, $ } = Admin;

Admin.onStatus((status) => {
  const policy = status.updatePolicy || {};
  // "Required" is not a field of its own: it is the minimum and the latest being the same
  // version, which is what the client compares against.
  const required = Boolean(policy.minimumVersion) && policy.minimumVersion === policy.latestVersion;
  const destructive = Boolean(policy.retireBelowVersion) &&
    policy.retireBelowVersion === policy.latestVersion;

  $('update-state').innerHTML = !policy.enabled
    ? ui.tag('off', 'idle')
    : ui.tag((destructive ? 'sign-out · ' : required ? 'required · ' : 'optional · ') +
      policy.latestVersion, required ? 'warn' : 'ok');

  Admin.fill($('update-version'), policy.latestVersion || '');
  Admin.fill($('update-url'), policy.downloadUrl || '');
  Admin.fill($('update-notes'), policy.notes || '');
  Admin.fill($('update-retire-below'), policy.retireBelowVersion || '');
  Admin.check($('update-required'), required);
  Admin.check($('update-destructive'), destructive);
});

const body = (enabled) => JSON.stringify({
  enabled,
  latestVersion: $('update-version').value.trim(),
  downloadUrl: $('update-url').value.trim(),
  notes: $('update-notes').value.trim(),
  required: $('update-required').checked,
  destructive: $('update-destructive').checked,
  retireBelowVersion: $('update-retire-below').value.trim(),
});

Admin.ready(() => {
  $('update-destructive').addEventListener('change', () => {
    if ($('update-destructive').checked) {
      $('update-required').checked = true;
      $('update-retire-below').value = $('update-version').value.trim();
    } else if ($('update-retire-below').value.trim() === $('update-version').value.trim()) {
      $('update-retire-below').value = '';
    }
  });
  $('update-save').addEventListener('click', () => {
    const destructive = $('update-destructive').checked;
    const warning = destructive
      ? 'This will delete sessions on every older television and force viewers to sign in again after updating. Continue?'
      : 'Required updates block the home screen on every television below this version. Continue?';
    if ($('update-required').checked && !confirm(warning)) return;
    Admin.act(() => Admin.api('/admin/api/update-policy', { method: 'POST', body: body(true) }));
  });
  $('update-disable').addEventListener('click', () =>
    Admin.act(() => Admin.api('/admin/api/update-policy', { method: 'POST', body: body(false) })));
});
