// Get the link element
const link = document.querySelector('.hamburger');
var converter = null;
var references = {};

// Add an event listener to the link
if (link) {
    link.addEventListener('click', function () {
        // Toggle the class of the link to open or close the menu
        document.querySelector('ul.hamburger-list').classList.toggle('menu-open');
    });
}

function setHeight() {
    converter = new showdown.Converter();
    converter.setFlavor('github');

    body = document.querySelector('body');
    body.style.height = window.innerHeight + 'px';

    cont = document.querySelector('.container');
    cont.style.height = (window.innerHeight - 50) + 'px';

    tabs = document.querySelector('.ref-tab');
    tabs.style.height = (window.innerHeight - 60) + 'px';

    ref = document.querySelector('.ref');
    ref.style.height = (window.innerHeight - 125) + 'px';

    notes = document.querySelector('.notes');
    notes.style.height = (window.innerHeight - 150) + 'px';

    setTimeout(saveNote, 5000);
}

function newNote() {
    notes = document.querySelector('.notes');
    notes.textContent = '';
}

function openNote() {

}

function saveNote(event) {
    event.preventDefault();

    if(!validateNote()) {
        setTimeout(saveNote, 5000);
        return;
    }
    fetch('/index.php/save-note', {
        method: 'POST',
        headers: {
            "Content-Type": 'application/x-www-form-urlencoded'
        },
        body: {
            title: document.querySelector('#noteTitle').value,
            speaker: document.querySelector('#speaker').value,
            series: document.querySelector('#series').value,
            note: document.querySelector('#notes').textContent
        }
        .then(response => response.text)
        .then(results => {
            results = JSON.parse(results);
            alert(results);
            showSave();
        })
    });
    setTimeout(saveNote, 5000);
}

function validateNote() {
    const note = document.querySelector('#notes');
    const speaker = document.querySelector('#speaker');
    const series = document.querySelector('#series');
    const title = document.querySelector('#noteTitle');

    if(!title.value.length) {return false;}

    if(!speaker.value) {return false;}

    if(!series.value) {return false;}

    if(!note.textContent.length) {return false;}

    return true;
}

function showSave() {// Get the element that will display the checkmark
    var checkmark = document.getElementById("save-check");
    
    // Schedule the animation to run every 1 second (which is equivalent to a 1-second delay between each iteration)
    setInterval(function() {
      // Increment the opacity of the checkmark by 0.01 each time
      checkmark.style.opacity += 0.1;
      
      // If the opacity is greater than or equal to 1, reset it back to 0 and stop the animation
      if (checkmark.style.opacity >= 1) {
        checkmark.style.opacity = 0;
        clearInterval(setInterval);
      }
    }, 100);
}

/**
 * Function to discard the note by clearing all input fields and closing the menu.
 */
function discardNote() {
    document.querySelector('#noteTitle').value = '';
    document.querySelector('#speaker').value = 0;
    document.querySelector('#series').value = 0;
    document.querySelector('#template').value = 0;
    document.querySelector('#notes').value = '';

    openRef();
}

function openRef() {
    refQuery = document.querySelector('#refQuery');
    if (refQuery.style.display === 'block') {
        refQuery.style.display = 'none';
    } else {
        refQuery.style.display = 'block';
    }

    menu = document.querySelector('ul.hamburger-list');
    refQuery.style.left = (menu.clientLeft + menu.clientWidth) + 'px';
    refQuery.style.top = (menu.clientTop + menu.clientHeight) + 'px';
}

function queryRef() {
    const input = document.querySelector('#refQuery #search');
    fetch('/index.php/retrieve-reference', {
        method: 'POST',
        headers: {
            'Content-Type': 'plain/text'
        },
        body: JSON.stringify({
            'reference': input.value
        })
    })
        .then(response => response.text())
        .then(results => {
            results = JSON.parse(results);

            const list = document.querySelector('#ref-list');
            var newList = document.createElement('li');
            newList.className = 'tab';
            var button = document.createElement('button');
            button.innerText = results.title;
            button.onclick = function () {
                document.querySelector('#ref').innerHTML = converter.makeHtml(references[button.innerText]);
            }
            button.ondblclick = function () {
                document.querySelector('#ref').innerHTML = '';
                delete references[results.title];
                var list = button.parentElement;
                list.remove();
            }
            newList.appendChild(button);
            list.appendChild(newList);

            const ref = document.querySelector('#ref');
            ref.innerHTML = converter.makeHtml(results.text);

            references[results.title] = results.text;

            input.value = '';
            openRef();
            link.click();
        });
}

function retrieveTemplate(orig, dest) {
    const temp = document.querySelector('#' + orig);
    if (temp.value == '0') {
        document.querySelector('#' + dest).value = '';
        return;
    }
    fetch('/index.php/retrieve-template', {
        method: 'POST',
        headers: {
            'Content-Type': 'plain/text'
        },
        body: JSON.stringify({
            'template': temp.value
        })
    })
        .then(response => response.text())
        .then(results => {
            const div = document.querySelector('#' + dest);
            div.value = results;
        });
}

/**
 * Saves the template by sending a POST request to the server with template data.
 */
function saveTemplate() {
    fetch('/index.php/save-template', {
        method: 'POST',
        headers: {
            'Content-Type': 'plain/text'
        },
        body: JSON.stringify({
            'template_id': document.querySelector('#template_id').value,
            'template_name': document.querySelector('#template_name').value,
            'template_value': document.querySelector('#template_value').value,
        })
    })
        .then(response => response.text())
        .then(results => {
            alert(results);
        });
}

function retrieveSeries() {

}

function saveSeries() {

}

function retrieveSpeaker() {

}

function saveSpeaker() {

}

function referenceEditor() {
}
