{% extends 'base.html' %}

{% block header %}
{% if term.language_id is none %}New Term{% else %}Edit Term{% endif %}
{% endblock %}

{% block body %}
<div id="term_form_left">
  {% include('term/_form.html') %}
  <a href="/term/index">Back to list</a>
</div>


<div id="term_form_right">
  <div class="dictcontainer">
    <div id="dicttabs">
      <div id="dicttabslayout"></div>
      <div id="dicttabsstatic"></div>
    </div>
    <div id="dictframes"></div>
  </div>
</div>

{% if term.language_id is none %}

  <script>
    const dictTabsContainer = document.getElementById("dicttabs");
    const loadDictsBtn = document.getElementById("load-dicts-btn");
    const langSelect = document.getElementById("language_id");
    const termField = document.getElementById("text");
    let old_term = "";
    let old_langid = 0;

    const ALL_DICTS = {{ language_dicts | safe }};
    LookupButton.TERM_FORM_CONTAINER = document.getElementById("term-form-container");
    LookupButton.LANG_ID = 0;
    LookupButton.TERM_DICTS = [];

    loadDictsBtn.addEventListener("click", (e) => {
      e.preventDefault();

      let selected_lang_id = langSelect.value;
      if (selected_lang_id == 0 || !termField.value)
        return;

      const lang_changed = selected_lang_id != old_langid;
      const term_changed = termField.value != old_term;
      if (lang_changed) {
        // New language = new buttons, rebuild it all.
        LookupButton.LANG_ID = selected_lang_id;
        LookupButton.TERM_DICTS = ALL_DICTS[selected_lang_id].term;
        createLookupButtons();
      }
      if (lang_changed || term_changed) {
        // Refresh the tabs if needed.
        LookupButton.LANG_ID = selected_lang_id;
        loadDictionaries();
      }

      old_term = termField.value;
      old_langid = selected_lang_id;
      
    })
  </script>

{% else %}

  <script>
    const ALL_DICTS = {{ language_dicts | safe }};
    LookupButton.TERM_FORM_CONTAINER = document.getElementById("term-form-container");
    LookupButton.LANG_ID = $('#language_id').val();
    LookupButton.TERM_DICTS = ALL_DICTS[LookupButton.LANG_ID].term;
    createLookupButtons();
    loadDictionaries();
  </script>

{% endif %}

{% endblock %}
