{% extends 'trosnoth/base.html' %}
{% load static %}
{% block head %}
  <title>{{ settings.serverName }} :: Select Scenario</title>
{% endblock %}

{% block main %}
  <div id="container">
    <h1><a href="/">{{ settings.serverName }}</a></h1>
    <h2>Select scenario</h2>
    {% if not loneArena %}
      <p class="form_note">This scenario will be run in arena "{{ arena.name }}".</p>
    {% endif %}

    <form method="post">
      {% csrf_token %}
      <table>{{ form.as_table }}</table>
      <div class="submit-row">
        <input type="submit" class="default" value="Start scenario">
        <input type="submit" value="Cancel" name="cancel">
      </div>
    </form>
  </div>
  {{ form.level_data|json_script:"level-data" }}
  <script>
    const level_data = JSON.parse(document.getElementById('level-data').textContent);
    function update_fields() {
      const scenario = document.getElementById('id_scenario').value;

      const teams_field = document.getElementById('id_teams');
      const team_options = level_data[scenario].team_options;
      let first_index = -1;
      for (let i = 0; i < teams_field.children.length; i++) {
        let child = teams_field.children[i];
        if (team_options[child.value]) {
          child.style.display = "";
          if (first_index < 0) {
            first_index = i;
          }
        } else {
          child.style.display = "none";
        }
      }
      if (!team_options[teams_field.value] && first_index >= 0) {
        teams_field.selectedIndex = first_index;
      }

      const size_field = document.getElementById('id_size');
      const size_options = level_data[scenario].size_options;
      first_index = -1;
      for (let i = 0; i < size_field.children.length; i++) {
        let child = size_field.children[i];
        if (size_options[child.value]) {
          child.style.display = "";
          if (first_index < 0) {
            first_index = i;
          }
        } else {
          child.style.display = "none";
        }
      }
      if (!size_options[size_field.value] && first_index >= 0) {
        size_field.selectedIndex = first_index;
      }
    }
    window.onload = update_fields;
  </script>
{% endblock %}