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

let filesList = []

let fileMetaData = []

async function fetchImages() {
    await $.ajax({
        url: '/files',
        type: 'GET',
        success: function(response) {
            filesList = response;
            console.log(filesList);
        },
        error: function() {
            alert('Error fetching images.');
        }
    });
    
    filesList.ImageNames.forEach((filePath, i) => {
        let newRow = $(`
                <tr>
                    <td>`+ i +`</td>
                    <td>
                        <img src="` + filePath + `" class="gallery-image" />
                    </td>
                        <td class="spice-slider-td">
                            <output id="spice-output-` + i + `">0</output>
                            <input type="range" min="0" max="10" value="` + 0 + `" class="spice-slider" id="spice-slider-` + i + `" />
                        </td>
                    </tr>
            `);
        galleryTable.append(newRow);

        fileMetaData.push({
            "id": i,
            "spice_level": 0,
            "path": filePath
        });
    });
    fileMetaData.forEach(file => {
        $("#spice-slider-" + file.id).on("input", function() {
            file.spice_level = this.value;
            $("#spice-output-" + file.id).text(this.value);
            console.log(fileMetaData);
        })
    });
}

refreshButton.on("click", function() {
    galleryTable.empty();
    fetchImages();
});

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