$(document).ready(function() {
    console.log('Document is ready');

    var printersData = [];

    // Fetch printer data from the server when the page loads
    $.get('/get_printers', function(data) {
        console.log('Fetched printer data:', data);
        printersData = data;
        data.forEach(function(printer) {
            $('#printers').append(new Option(printer["display-name"], printer["display-name"]));
        });
        console.log('Printers dropdown populated');
    }).fail(function() {
        console.error('Failed to fetch printer data');
    });

    // Handle printer selection change
    $('#printers').change(function() {
        var selectedPrinter = $(this).val();
        console.log('Printer selected:', selectedPrinter);
        if (selectedPrinter) {
            var printer = printersData.find(p => p["display-name"] === selectedPrinter);
            console.log('Selected printer data:', printer);
            if (printer) {
                var mediaSizesHtml = '<ul>';
                printer['media-sizes'].forEach(function(media) {
                    mediaSizesHtml += '<li>';
                    mediaSizesHtml += '<input type="checkbox" ' + (media.enabled ? 'checked' : '') + '>';
                    mediaSizesHtml += '<span>' + media['media-size-display'] + ' - (' + media['capacity'] + ')' + '</span>';
                    mediaSizesHtml += '</li>';
                });
                mediaSizesHtml += '</ul>';
                $('#media-sizes').html(mediaSizesHtml);
                console.log('Media sizes displayed for selected printer');
            }
        } else {
            $('#media-sizes').html('');
            console.log('No printer selected, media sizes cleared');
        }
    });

    // Handle save button click
    $('#save').click(function() {
        var selectedPrinter = $('#printers').val();
        console.log('Save button clicked for printer:', selectedPrinter);
        if (selectedPrinter) {
            var printer = printersData.find(p => p["display-name"] === selectedPrinter);
            if (printer) {
                printer['media-sizes'] = [];
                $('#media-sizes li').each(function() {
                    var enabled = $(this).find('input').is(':checked');
                    var mediaSizeDisplay = $(this).find('span').text();
                    var mediaSize = mediaSizeDisplay.match(/\(([^)]+)\)/)[1]; // Extract media-size from display text
                    printer['media-sizes'].push({ "enabled": enabled, "media-size": mediaSize, "media-size-display": mediaSizeDisplay });
                });
                console.log('Updated printer data to be saved:', printersData);
                $.ajax({
                    url: '/save_printers',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(printersData),
                    success: function(response) {
                        console.log('Save response:', response);
                        alert('Changes saved successfully!');
                    },
                    error: function() {
                        console.error('Failed to save changes');
                    }
                });
            }
        } else {
            console.warn('Please select a printer before saving');
            alert('Please select a printer.');
        }
    });
});
