$(document).ready(function() {
    var printersData = [];

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

    // Handle printer selection change
    $('#printers').change(function() {
        var selectedPrinter = $(this).val();
        if (selectedPrinter) {
            var printer = printersData.find(p => p["display-name"] === selectedPrinter);
            if (printer) {
                var mediaSizesHtml = '<ul>';
                printer['media-sizes'].forEach(function(media) {
                    mediaSizesHtml += '<li>';
                    mediaSizesHtml += '<input type="checkbox" ' + (media.enabled ? 'checked' : '') + '>';
                    mediaSizesHtml += '<span>' + 'Size = ' + media['media-size-display'] + ' - cap = ' + media['capacity']  + '</span>';
                    mediaSizesHtml += '</li>';
                });
                mediaSizesHtml += '</ul>';
                $('#media-sizes').html(mediaSizesHtml);
            }
        } else {
            $('#media-sizes').html('');
        }
    });

    // Handle checkbox change event
    $(document).on('change', '#media-sizes input[type="checkbox"]', function() {
        var selectedPrinter = $('#printers').val();
        if (selectedPrinter) {
            var printer = printersData.find(p => p["display-name"] === selectedPrinter);
            if (printer) {
                $('#media-sizes li').each(function(index) {
                    var enabled = $(this).find('input').is(':checked');
                    printer['media-sizes'][index].enabled = enabled;
                });
            }
        }
    });

    // Handle save button click
    $('#save').click(function() {
        var selectedPrinter = $('#printers').val();
        if (selectedPrinter) {
            var printer = printersData.find(p => p["display-name"] === selectedPrinter);
            if (printer) {
                $.ajax({
                    url: '/save_printers',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(printersData),
                    success: function(response) {
                        alert('Changes saved successfully!');
                    },
                    error: function() {
                        console.error('Failed to save changes');
                    }
                });
            }
        } else {
            alert('Please select a printer.');
        }
    });
});
