const inputBox = document.querySelector("#input-box");
const todoListContainer = document.querySelector("#todo-list-container");

function neueAufgabe(){
    inputBox.focus();

    if (inputBox.value === '') {
        return;
    }

    saveData({'data' : inputBox.value, 'checked': false, 'index' : todoListContainer.childNodes.length});
    loadData();

    inputBox.value = '';
}

function buildListItem(data, checked, index){
    let listElement = document.createElement('li');
    let checkBox = document.createElement('input');
    checkBox.setAttribute('type', 'checkbox');
    checkBox.setAttribute('id', `list-entry-${index}`);
    checkBox.addEventListener('click', () => {saveData(); loadData();});
    let listLable = document.createElement('label');
    listLable.textContent = data;
    listLable.setAttribute('for', `list-entry-${index}`);
    listElement.appendChild(checkBox);
    listElement.appendChild(listLable);
    if (checked) {
        checkBox.checked = true;
        listLable.classList.add('checked-list-item');
    } else {
        let removeButton = document.createElement('button');
        removeButton.innerHTML = '<i class="material-icons">delete</i>';
        removeButton.addEventListener('click', () => {listElement.remove();saveData();loadData();});
        listElement.appendChild(removeButton);
    }
    return listElement;
}

function loadData(){

    todoListContainer.innerHTML = '';

    let data = JSON.parse(localStorage.getItem('data')) || [];

    data.forEach((listItem, index) => {
        todoListContainer.appendChild(buildListItem(listItem.data, listItem.checked, index));
    });
}

function saveData(newItem = null)
{

    let todoItems = [];

    if (todoListContainer.childNodes.length !== 0) {
        todoListContainer.childNodes.forEach((todoItem, index) => {
            let data = todoItem.querySelector('label').textContent;
            let checked = todoItem.querySelector('input').checked;
            todoItems.push({data, checked, index});
        });
    }
    if (newItem) {
        todoItems.push(newItem);
    }

    localStorage.setItem('data', JSON.stringify(todoItems));
}

function handleKeyPress(event){

    if (event.key === "Enter") {
        neueAufgabe();
    }
}

loadData();