$( document ).ready(function() {
    $('#abv-select-lang').on('input', function() {
        let $selected = $(this).children('option:selected');
        let url = `./api/languages/${$selected.attr('value')}`;

        fetch(url)
        .then(res => res.json())
        .then(out => {
          let $select_word = $('#abv-select-word');
          let $select_entry = $('#abv-select-entry');
          $select_word.empty();
          $select_entry.empty();
          for (w of out.words) {
                $select_word.append(new Option(w.text,w.id))
            }
        })
        .catch(err => console.log(err));
    });

    $('#abv-select-word').on('input', function() {
        let $selected = $(this).children('option:selected');
        let wordid = $selected.attr('value');
        let lang = $('#abv-select-lang').children('option:selected').attr('value');
        let url = `./api/languages/${lang}/words/${wordid}`;

        fetch(url)
        .then(res => res.json())
        .then(out => {
          let $select_entry = $('#abv-select-entry');
          $select_entry.empty();
          for (e of out.entries) {
                url_entry = `./api/entries/${e.id}`;
                fetch(url_entry)
                .then(res => res.json())
                .then(out => {
                    let entrystring = '';
                    let glosses = [];
                    for (r of e.refs) {
                        if (r.glosses) {
                            for(g of r.glosses){
                                glosses.push(`‘${g}’`);
                            }
                        }
                    }
                    if(glosses.length > 0) {
                        entrystring = `${glosses.join('; ')}: `
                    }
                    opt = $(`<option value="${out.xmlid}" data-abv-xpath="${e.refs[0].path}">${entrystring}<i>${out.form}</i>
                            ${out.glosses.map(g => `‘${g}’`).join(', ')}</option>`);
                    $select_entry.append(opt)
                })
                .catch(err => console.log(err));
            }
        })
        .catch(err => console.log(err));
    });

    $('#abv-select-entry').on("dblclick", function() {
        let $selected = $(this).children('option:selected');
        let entry = $selected.attr('value');
        let path = $selected.attr('data-abv-xpath');
        window.location.replace('./dict/' + entry + `?entry=${entry}&xpath=${path}`);
    });
});
