var selectedRow = null


function onFormSubmit() {
    var formData = readFormData();
    if (selectedRow == null)
        insertNewRecord(formData);
    else
        updateRecord(formData);
    resetForm();
}

function readFormData() {
    var formData = {};
    formData["aliment"] = document.getElementById("aliment").value;
    formData["type"] = document.getElementById("type").value;
   
    return formData;
}

function insertNewRecord(data) {
    var table = document.getElementById("table_aliments").getElementsByTagName('tbody')[0];
    var newRow = table.insertRow(table.length);
    cell1 = newRow.insertCell(0);
    cell1.innerHTML = data.aliment;
    cell2 = newRow.insertCell(1);
    cell2.innerHTML = data.type;
    cell3 = newRow.insertCell(2);
    cell3.innerHTML = `<a onClick="onAdd(this)" href="index.php?page=journal">Add</a>`;
    cell4 = newRow.insertCell(3);
    cell4.innerHTML = `<a onClick="onEdit(this)">Edit</a>
                       <a onClick="onDelete(this)">Delete</a>`;
}

function resetForm() {
    document.getElementById("aliment").value = "";
    document.getElementById("type").value = "";
    selectedRow = null;
}

function onAdd(td){
    selectedRow=td.parentElement.parentElement;
    var table1 = document.getElementById("table_conso").getElementsByTagName('tbody')[0];
    var newRow1 = table1.insertRow(table1.length);
    cell1 = newRow1.insertCell(0);
    cell1.innerHTML = selectedRow.cells[0].innerHTML;
    cell2 = newRow1.insertCell(1);
    cell2.innerHTML = selectedRow.cells[1].innerHTML; 
    
}

function onEdit(td) {
    selectedRow = td.parentElement.parentElement;
    document.getElementById("aliment").value = selectedRow.cells[0].innerHTML;
    document.getElementById("type").value = selectedRow.cells[1].innerHTML;
}
function updateRecord(formData) {
    selectedRow.cells[0].innerHTML = formData.aliment;
    selectedRow.cells[1].innerHTML = formData.type;
}

function onDelete(td) {
    if (confirm("Supprimer l'élément ?")) {
        row = td.parentElement.parentElement;
        document.getElementById("table_aliments").deleteRow(row.rowIndex);
        resetForm();
    }
}