<!DOCTYPE html>
<html>
<head>
    <title>Fencing Gallery🤺</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='gallery_styles.css') }}">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js"></script>
</head>
<body>
    <div class="button-container">
        <a href="{{ url_for('gallery') }}" class="button">🤺🤺🤺</a>
        <a href="{{ url_for('dump') }}" class="button">🎃🎃🎃</a>
    </div>
    <h1>Fencing Gallery🤺</h1>
    <div class="gallery-container" id="gallery-container">
        {% for batch in batches %}
            {% set batch_number = batch[0].split('_')[0] if batch and '_' in batch[0] else 'unstructured' %}
            <div class="batch-container batch-{{ batch_number }}">
                {% for image in batch %}
                    {% if '_' in image and '.' in image.split('_')[1] %}
                        {% set index = image.split('_')[1].split('.')[0] %}
                    {% else %}
                        {% set index = 'unstructured' %}
                    {% endif %}
                    <a href="#" data-original="{{ url_for('uploaded_file', filename=image) }}" target="_blank">
                        <img class="responsive-img index-{{ index }}" src="{{ url_for('cached_file', filename=image) }}" alt="{{ image }}">
                    </a>
                {% endfor %}
            </div>
            {% if not loop.last %}
                <hr>
            {% endif %}
        {% endfor %}
    </div>
    <script>
        var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);

        function parseImageName(image) {
            var parts = image.split('_');
            if (parts.length === 2) {
                var batchNumber = parseInt(parts[0], 10);
                var index = parseInt(parts[1].split('.')[0], 10);
                return { batchNumber: batchNumber, index: index };
            }
            return { batchNumber: 0, index: 0 };
        }

        function removeNonExistentImages(existingImages, images) {
            var galleryContainer = document.getElementById('gallery-container');
            existingImages.forEach(function(image) {
                if (!images.includes(image)) {
                    var imgElement = galleryContainer.querySelector(`img[alt="${image}"]`);
                    if (imgElement) {
                        imgElement.parentElement.classList.add('removed');
                        setTimeout(() => {
                            imgElement.parentElement.remove();
                        }, 500); // Match the duration of the fadeOut animation
                    }
                }
            });
        }

        function addNewImages(existingImages, images) {
            var galleryContainer = document.getElementById('gallery-container');
            var currentBatchContainer = null;
            var currentBatchNumber = null;

            images.forEach(function(image) {
                if (!existingImages.includes(image)) {
                    var parsedImage = parseImageName(image);
                    var batchNumber = parsedImage.batchNumber;
                    var index = parsedImage.index;

                    if (currentBatchNumber !== batchNumber) {
                        currentBatchNumber = batchNumber;
                        currentBatchContainer = document.querySelector(`.batch-${batchNumber}`);
                        if (!currentBatchContainer) {
                            currentBatchContainer = document.createElement('div');
                            currentBatchContainer.className = `batch-container batch-${batchNumber}`;
                            galleryContainer.appendChild(currentBatchContainer);

                            if (galleryContainer.children.length > 1) {
                                var divider = document.createElement('hr');
                                galleryContainer.insertBefore(divider, currentBatchContainer);
                            }
                        }
                    }

                    var anchor = document.createElement('a');
                    anchor.href = '#';
                    anchor.setAttribute('data-original', `/images/${image}`);
                    anchor.target = '_blank';
                    anchor.classList.add('added');

                    var img = document.createElement('img');
                    img.className = `responsive-img index-${index}`;
                    img.alt = image;
                    img.src = `/cached/${image}`;

                    anchor.appendChild(img);

                    // Insert the image in the correct location based on the index
                    var inserted = false;
                    var children = currentBatchContainer.children;
                    for (var i = 0; i < children.length; i++) {
                        var childIndex = parseInt(children[i].querySelector('img').className.split('index-')[1], 10);
                        if (index < childIndex) {
                            currentBatchContainer.insertBefore(anchor, children[i]);
                            inserted = true;
                            break;
                        }
                    }
                    if (!inserted) {
                        currentBatchContainer.appendChild(anchor);
                    }

                    img.addEventListener('load', function() {
                        img.classList.add('loaded');
                    });
                    if (img.complete) {
                        img.classList.add('loaded');
                    }

                    anchor.addEventListener('click', function(event) {
                        event.preventDefault();
                        var originalUrl = anchor.getAttribute('data-original');
                        window.open(originalUrl, '_blank');
                    });
                }
            });
        }

        socket.on('update_gallery', function() {
            fetch('/api/images')
                .then(response => response.json())
                .then(images => {
                    var galleryContainer = document.getElementById('gallery-container');
                    var existingImages = Array.from(galleryContainer.getElementsByTagName('img')).map(img => img.alt);

                    removeNonExistentImages(existingImages, images);
                    addNewImages(existingImages, images);
                });
        });

        document.addEventListener("DOMContentLoaded", function() {
            var images = document.querySelectorAll('.responsive-img');
            images.forEach(function(img) {
                img.addEventListener('load', function() {
                    img.classList.add('loaded');
                });
                if (img.complete) {
                    img.classList.add('loaded');
                }
            });

            var links = document.querySelectorAll('.gallery-container a');
            links.forEach(function(link) {
                link.addEventListener('click', function(event) {
                    event.preventDefault();
                    var originalUrl = link.getAttribute('data-original');
                    window.open(originalUrl, '_blank');
                });
            });
        });
    </script>
</body>
</html>