import { state } from './state.js';
import { closeRef, makeButton } from './home.js';
import { saveNote, findRefLinks, closePopup } from './note.js';

/**
 * 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',
        headers: {
            '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",
        headers: {
            "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',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            refId: ref.value,
            text: cont.value
        })
    })
        .then(response => response.json())
        .then(results => {
            document.querySelector('#reference').value = '';
            document.querySelector('#referenceType').value = '';
            document.querySelector('#referenceSeries').value = '';
        });
}

/**
 * Retrieves the list of books based on the selected reference type.
 *
 * @return {void}
 */
export function retrieveBooks() {
    document.querySelector('#chapter-range').innerText = '';
    document.querySelector('#verse-range').innerText = '';
    document.querySelector('#referenceSearch').value = '';
    document.querySelector('#referenceSearch').style.display = 'none';
    const selectedType = document.querySelector('#referenceType').value;
    if (!selectedType) { return; }

    var bookList = document.querySelector('#referenceBook');
    bookList.style.display = "block";
    bookList.innerHTML = '';
    if (selectedType == 'bible') {
        document.querySelector('#referenceSearch').style.display = 'block';
        var none = document.createElement("option");
        none.value = '';
        none.text = '-- Select --';
        bookList.appendChild(none);
        for (var x in state.BOOKS.bible) {
            var newBook = document.createElement("option");
            newBook.text = x;
            bookList.appendChild(newBook);
        }
    } else if (selectedType == 'creed') {
        var none = document.createElement('option');
        none.value = '';
        none.text = '-- Select --';
        bookList.appendChild(none);
        for (var x in state.BOOKS.creed) {
            var newBook = document.createElement('option');
            newBook.value = x;
            newBook.text = state.BOOKS.creed[x];
            bookList.appendChild(newBook);
        }
    } else if (selectedType == 'cd') {
        var none = document.createElement("option");
        none.value = '';
        none.text = '-- Select --';
        bookList.appendChild(none);
        for (var x in state.BOOKS.cd) {
            var newBook = document.createElement("option");
            newBook.text = state.BOOKS.cd[x];
            bookList.appendChild(newBook);
        }
    } else if (selectedType == 'hc') {
        var none = document.createElement("option");
        none.value = '';
        none.text = '-- Select --';
        bookList.appendChild(none);
        for (var x in state.BOOKS[selectedType]) {
            var newBook = document.createElement("optgroup");
            newBook.label = "Lord's Day " + (parseInt(x) + 1)
            var ld = document.createElement("option");
            ld.value = 'ld' + (parseInt(x) + 1);
            ld.text = "LD " + (parseInt(x) + 1) + " All";
            newBook.appendChild(ld);

            for (var y in state.BOOKS[selectedType][x]) {
                var question = document.createElement("option");
                question.value = 'hc' + state.BOOKS[selectedType][x][y];
                question.text = "HC" + state.BOOKS[selectedType][x][y];
                newBook.appendChild(question);
            }
            bookList.appendChild(newBook);
        }
    } else if (selectedType == 'note') {
        var none = document.createElement("option");
        none.value = '';
        none.text = '-- Select --';
        bookList.appendChild(none);

        fetch('/retrieve-reference', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                'type': 'note'
            })
        })
            .then(response => response.json())
            .then(results => {
                for (var x in results) {
                    var newBook = document.createElement("option");
                    newBook.value = results[x].id;
                    newBook.text = results[x].title;
                    bookList.appendChild(newBook);
                }
            });
    } else {
        var min = state.BOOKS[selectedType][0];
        var max = state.BOOKS[selectedType][1];
        var none = document.createElement("option");
        none.value = '';
        none.text = '-- Select --';
        bookList.appendChild(none);
        for (var x = min; x <= max; x++) {
            var newBook = document.createElement("option");
            newBook.value = x;
            newBook.text = x;
            bookList.appendChild(newBook);
        }
    }
}

/**
 * Filters the books based on the selected reference type and updates the chapter range.
 *
 * @return {void} This function does not return anything.
 */
export function filterBooks() {
    document.querySelector('#chapter-range').innerText = '';
    document.querySelector('#verse-range').innerText = '';
    if (document.querySelector('#referenceType').value != 'bible') {
        return;
    }

    var bookList = document.querySelector('#referenceBook');
    var book = state.BOOKS.bible[bookList.value];
    var max = Object.keys(book).length;

    var chapterRange = document.querySelector('#chapter-range');
    chapterRange.innerText = 'Chapters: ' + max;
}

/**
 * Filters the verse based on the selected book and chapter.
 *
 * @return {void} This function does not return anything.
 */
export function filterVerse() {
    if (document.querySelector('#referenceType').value != 'bible') {
        return;
    }

    var bookList = document.querySelector('#referenceBook').value;
    var search = document.querySelector('#referenceSearch').value;
    var chapter = search.split(':')[0];
    var verseRange = document.querySelector('#verse-range');

    if (!state.BOOKS.bible[bookList] || !state.BOOKS.bible[bookList][chapter]) {
        verseRange.innerText = 'Unknown Chapter';
        return;
    }
    var verse = state.BOOKS.bible[bookList][chapter];
    verseRange.innerText = 'Verse: ' + verse;
}

/**
 * Fetches a reference based on the provided type, book, and input.
 *
 * @param {string} type - The type of reference.
 * @param {string} book - The book of the reference.
 * @param {string} input - The input for the reference.
 * @return {void} This function does not return anything directly, but processes the fetched reference data.
 */
export function queryRef(e, type = null, book = null, input = null) {
    if (!input) {
        var input = document.querySelector('#refQuery #referenceSearch').value;
    }
    if (!type) {
        var type = document.querySelector('#referenceType').value;
    }
    if (!book) {
        var book = document.querySelector('#referenceBook').value;
    }
    fetch('/retrieve-reference', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            'type': type,
            'book': book,
            'reference': input,
        })
    })
        .then(response => response.json())
        .then(results => {
            const list = document.querySelector('#ref-list');
            var newList = document.createElement('li');
            newList.className = 'tab';
            let button = makeButton(results.title);
            newList.appendChild(button);
            list.appendChild(newList);

            const ref = document.querySelector('#ref-text');
            ref.innerHTML = state.md.render(results.text);

            state.references[results.title] = results.text;

            closeRef();
            closePopup();

            state.saved = false;
            state.textDirty = true;
            saveNote();
            findRefLinks();
        });
}

