(function() {
  'use strict';

  var all_languages = {
      'de': 'German',
      'en': 'English',
      'fr': 'French',
      'it': 'Italian',
      'ja': 'Japanese',
      'ru': 'Russian',
  };

  function build_language_select(current_language) {
    if (!(current_language in all_languages)) {
      // In case we're browsing a language that is not yet in all_languages.
      all_languages[current_language] = current_language;
    }

    var select = document.createElement('select');
    select.setAttribute('id', 'language-selection');

    for (var [language, title] of Object.entries(all_languages)) {
      var option = document.createElement('option');
      option.setAttribute('value', language);
      option.append(title);
      select.append(option);
    };
    select.value = current_language;

    return select;
  }

  function navigate_to_first_existing(paths) {
    // Navigate to the first existing URL path in 'paths'.
    var path = paths.shift();
    if (paths.length == 0) {
      window.location.href = path;
      return;
    }
    fetch(path).then(response => {
      if (response.ok) window.location.pathname = path;
      else navigate_to_first_existing(paths);
    });
  }

  function on_language_switch(event) {
    var selected_language = event.target.value;
    var path = window.location.pathname;
    if (path.endsWith('/')) { // Special directory-index case.
      path += 'index.html';
    }
    var current_language = language_segment_from_path(path);
    if (selected_language == 'en') // Special 'default' case for english.
      selected_language = '';
    var new_path = path.replace(
      current_language ? `.${current_language}.html` : '.html',
      selected_language ? `.${selected_language}.html` : '.html'
    );
    if (new_path != path) {
      navigate_to_first_existing([
        new_path,
        'https://www.debian.org/doc/manuals/developers-reference/'
      ]);
    }
  }

  // Returns a language code if one is identified in the filename extension
  // or '' if not found.
  function language_segment_from_path(path) {
    var language_regexp = '[.]([a-z]{2}(?:-[a-z]{2})?)[.]html$';
    var match = path.match(language_regexp);
    if (match !== null)
        return match[1];
    return '';
  }

  document.addEventListener("DOMContentLoaded", () => {
    var release = DOCUMENTATION_OPTIONS.VERSION;
    var language_segment = language_segment_from_path(window.location.pathname);
    var current_language = language_segment.replace(/\/+$/g, '') || 'en';
    var language_select = build_language_select(current_language);

    document.querySelector('.language_switcher_placeholder').replaceWith(language_select);
    language_select.addEventListener('change', on_language_switch);
  });
})();
