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;

  $('update-state').innerHTML = !policy.enabled
    ? ui.tag('off', 'idle')
    : ui.tag((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.check($('update-required'), required);
});

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,
});

Admin.ready(() => {
  $('update-save').addEventListener('click', () => {
    if ($('update-required').checked && !confirm('Required updates block the home screen on ' +
      'every television below this version. Continue?')) 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) })));
});
