import { state } from './state.js';

/**
 * A description of the entire function.
 */
export function newSeries() {
    if (document.querySelector('#series').value == 'new') {
        document.querySelector('#newSeries').style.display = 'inline-block';
        document.querySelector('#series').style.display = 'none';
    }

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

/**
 * Saves a series by making a POST request to '/save-series' with the series name as the request body.
 *
 * @param {Event} event - The keydown event.
 * @return {Promise} A Promise that resolves with the response from the server.
 */
export function saveSeries(event) {
    if (event.keyCode == 27) {
        document.querySelector('#newSeries').style.display = 'none';
        document.querySelector('#series').style.display = 'inline-block';
        document.querySelector('#series').value = 0;
    }
    if (event.keyCode == 13 && document.querySelector('#newSeries').value != '') {
        fetch('/save-series', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                'seriesName': document.querySelector('#newSeries').value
            })
        })
            .then(response => response.json())
            .then(results => {
                var newSeries = document.createElement('option');
                newSeries.text = document.querySelector('#newSeries').value;
                newSeries.value = results.id;
                document.querySelector('#series').add(newSeries);

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

                document.querySelector('#newSeries').value = '';
                document.querySelector('#series').value = results.id;
            });
    }
}

