import { state } from './state.js';
/**
 * Toggles the display of the new speaker input field and hides the speaker select field.
 *
 * @return {void} This function does not return anything.
 */
export function newSpeaker() {
    if (document.querySelector('#speaker').value == 'new') {
        document.querySelector('#newSpeaker').style.display = 'inline-block';
        document.querySelector('#speaker').style.display = 'none';
    }

    state.saved = false;
    state.textDirty = true;
}

/**
 * Saves a new speaker to the database and updates the UI with the new speaker option.
 *
 * @param {Event} event - The keydown event triggered by the user.
 * @return {Promise} A Promise that resolves with the results of the fetch request.
 */
export function saveSpeaker(event) {
    if (event.keyCode == 27) {
        document.querySelector('#newSpeaker').style.display = 'none';
        document.querySelector('#speaker').style.display = 'inline-block';
        document.querySelector('#speaker').value = 0;
    }
    if (event.keyCode == 13 && document.querySelector('#newSpeaker').value != '') {
        fetch('/save-speaker', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                'speakerName': document.querySelector('#newSpeaker').value
            })
        })
            .then(response => response.json())
            .then(results => {
                var newSpeaker = document.createElement('option');
                newSpeaker.text = document.querySelector('#newSpeaker').value;
                newSpeaker.value = results.id;
                document.querySelector('#speaker').add(newSpeaker);

                alert(results.msg);
                document.querySelector('#newSpeaker').style.display = 'none';
                document.querySelector('#speaker').style.display = 'inline-block';

                document.querySelector('#newSpeaker').value = '';
                document.querySelector('#speaker').value = results.id;
            });
    }
}
