let galleryTable = $("#imagesGallery")
let refreshButton = $("#refresh-gallery")
let saveButton = $("#save-gallery")

let fileMetaData = []

async function fetchImages() {
    await $.ajax({
        url: '/files',
        type: 'GET',
        success: function(response) {
            fileMetaData = response;
            console.log(fileMetaData);
        },
        error: function() {
            alert('Error fetching images.');
        }
    });
    
    fileMetaData.forEach((file, i) => {
        let newRow = $(`
                <tr>
                    <td>`+ i +`</td>
                    <td>
                        <img src="` + file.path + `" class="gallery-image" />
                    </td>
                        <td class="spice-slider-td">
                            <output id="spice-output-` + file.id + `">` + file.spice_level +`</output>
                            <input type="range" min="0" max="10" value="` + file.spice_level + `" class="spice-slider" id="spice-slider-` + file.id + `" />
                        </td>
                    </tr>
            `);
        galleryTable.append(newRow);
    });
    fileMetaData.forEach(file => {
        $("#spice-slider-" + file.id).on("input", function() {
            file.spice_level = Number(this.value);
            $("#spice-output-" + file.id).text(this.value);
            console.log(fileMetaData);
        })
    });
}
saveButton.on("click", function() {
    $.ajax({
        url: '/api/save-metadata',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(fileMetaData),
        success: function() {
            alert('Metadata saved successfully.');
        },
        error: function() {
            alert('Error saving metadata.');
        }
    });
})
refreshButton.on("click", function() {
    galleryTable.empty();
    fetchImages();
});

$( document ).ready(function() {        
    fetchImages();
});