const { fmt, ui, $ } = Admin;

Admin.onStatus((status) => {
  const subtitles = status.subtitles || {};
  const stored = subtitles.stored || {};

  $('subtitle-tiles').innerHTML = ui.tiles([
    ['offered on televisions', subtitles.available ? 'yes' : 'no',
      { small: true, icon: 'captions', tone: subtitles.available ? 'ok' : undefined }],
    ['providers on',
      fmt.number((subtitles.bazarrEnabled && subtitles.bazarrConfigured ? 1 : 0) +
        (subtitles.openSubtitlesEnabled ? 1 : 0)),
      { icon: 'list', tone: 'note' }],
    ['subtitles held', fmt.number(stored.count), { icon: 'database', tone: 'data' }],
    ['last fetched', fmt.when(stored.latest), { small: true, icon: 'clock' }],
  ]);

  Admin.check($('bazarr-enabled'), subtitles.bazarrEnabled);
  $('bazarr-enabled').disabled = !subtitles.bazarrConfigured;
  $('bazarr-state').innerHTML = !subtitles.bazarrConfigured
    ? ui.tag('not configured', 'idle')
    : (subtitles.bazarrEnabled ? ui.tag('on', 'ok') : ui.tag('off', 'idle'));
  // The address is worth printing: it is the one thing on this page an operator cannot
  // change here, so seeing which Bazarr is meant is how they find out it is the wrong one.
  $('bazarr-address').textContent = subtitles.bazarrConfigured
    ? 'Configured at ' + subtitles.bazarrUrl
    : 'Set MEMBY_BAZARR_URL and MEMBY_BAZARR_API_KEY to use Bazarr.';

  Admin.check($('opensubtitles-enabled'), subtitles.openSubtitlesEnabled);
  const keyField = $('opensubtitles-key');
  keyField.placeholder = subtitles.openSubtitlesKeyConfigured
    ? 'Saved key (leave blank to keep)' : 'Paste an API key';
  Admin.fill($('opensubtitles-username'), subtitles.openSubtitlesUsername || '');
  $('opensubtitles-state').innerHTML = subtitles.openSubtitlesEnabled
    ? ui.tag(subtitles.openSubtitlesAccount ? 'on · signed in' : 'on · anonymous',
      subtitles.openSubtitlesAccount ? 'ok' : 'warn')
    : ui.tag(subtitles.openSubtitlesKeyConfigured ? 'off · key saved' : 'off · no key', 'idle');

  // The feature flag overrides both switches, so a page that stayed silent about it would
  // be showing two controls that visibly do nothing.
  $('subtitle-hint').textContent = subtitles.featureEnabled
    ? 'A change applies to the next title opened; no app release is required.'
    : 'Downloading subtitles is switched off on the Features page, so nothing here is offered.';

  $('stored-state').innerHTML = stored.count
    ? ui.tag(fmt.number(stored.count) + ' files · ' + fmt.bytes(stored.bytes), 'data')
    : ui.tag('nothing held', 'idle');
  $('stored-clear').disabled = !stored.count;
});

const save = () => Admin.api('/admin/api/subtitle-settings', {
  method: 'POST',
  body: JSON.stringify({
    bazarrEnabled: $('bazarr-enabled').checked,
    openSubtitlesEnabled: $('opensubtitles-enabled').checked,
    openSubtitlesApiKey: $('opensubtitles-key').value.trim(),
    clearOpenSubtitlesApiKey: $('opensubtitles-clear-key').checked,
    openSubtitlesUsername: $('opensubtitles-username').value.trim(),
    openSubtitlesPassword: $('opensubtitles-password').value,
    clearOpenSubtitlesLogin: $('opensubtitles-clear-login').checked,
  }),
}).then(() => {
  // The credential fields are emptied on the way out, so a saved page never has a secret
  // sitting in a form somebody could walk past.
  $('opensubtitles-key').value = '';
  $('opensubtitles-password').value = '';
  $('opensubtitles-clear-key').checked = false;
  $('opensubtitles-clear-login').checked = false;
});

Admin.ready(() => {
  $('subtitle-save').addEventListener('click', () => Admin.act(save));

  $('subtitle-test').addEventListener('click', () => {
    const results = $('subtitle-test-results');
    results.innerHTML = ui.empty('Asking each provider…');
    Admin.api('/admin/api/subtitle-test', { method: 'POST' }).then((answer) => {
      const rows = answer.results || [];
      results.innerHTML = rows.length
        ? '<div class="list">' + rows.map((row) =>
          '<div class="list-row"><span class="list-main"><span>' +
          '<span class="list-title">' + fmt.escape(row.provider) + '</span>' +
          '<span class="list-meta">' + fmt.escape(row.message) + '</span></span></span>' +
          '<span class="list-actions">' + ui.tag(row.ok ? 'reachable' : 'not reachable',
            row.ok ? 'ok' : 'bad') + '</span></div>').join('') + '</div>'
        : ui.empty('No provider is switched on, so there was nothing to ask.');
    }).catch((error) => {
      results.innerHTML = ui.empty(String(error.message || error));
    });
  });

  $('stored-clear').addEventListener('click', () => {
    if (!confirm('Delete every subtitle Memby is holding? Each can be fetched again.')) return;
    Admin.act(() => Admin.api('/admin/api/subtitle-settings', {
      method: 'POST', body: JSON.stringify({ action: 'clear-stored' }),
    }));
  });
});
