/**
 * Retrieves the reference type from the server and populates the reference series dropdown.
 *
 * @param {HTMLElement} el - The element that triggered the function.
 * @return {Promise} A promise that resolves with the response from the server.
 */
export function retrieveReferenceType(el) {
    fetch('/reference/' + el.value, {
        method: 'GET',
        header: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => response.json())
        .then(results => {
            document.querySelector('#referenceSeries').innerHTML = '';
            var none = document.createElement('option');
            none.value = '';
            none.text = '-- Select --';
            document.querySelector('#referenceSeries').appendChild(none);

            for (var x in results) {
                var newSeries = document.createElement('option');
                newSeries.value = results[x].id;
                newSeries.text = results[x].label;
                document.querySelector('#referenceSeries').appendChild(newSeries);
            }
        });
}

/**
 * Retrieves a reference based on the provided element value.
 *
 * @param {Element} el - The element triggering the reference retrieval
 * @return {void} No return value
 */
export function retrieveReference(el) {
    if (el.value == 'new') {
        document.querySelector('#refName').style.display = 'inline-block';
        return;
    }
    fetch('/get-reference', {
        method: "POST",
        header: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            id: el.value
        })
    })
        .then(response => response.json())
        .then(results => {
            document.querySelector('#reference').value = results.text;
        });
}

/**
 * Saves a reference by sending a POST request to the server with the selected type,
 * file, and text values. Displays an alert with the response message, and clears
 * the reference and file input fields.
 *
 * @return {Promise} A Promise that resolves with the response message from the server.
 */
export function saveReference() {
    let ref = document.querySelector('#referenceSeries');
    let cont = document.querySelector('#reference');
    fetch('/save-reference', {
        method: 'POST',
        header: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            refId: ref.value,
            text: cont.value
        })
    })
        .then(response => response.json())
        .then(results => {
            //alert(results.msg);

            document.querySelector('#reference').value = '';
            document.querySelector('#referenceType').value = '';
            document.querySelector('#referenceSeries').value = '';
        });
}
