{% extends 'atlas/base.html' %}

{% block content %}
    <h2>Uploaded dicoms</h2>
    User: {{user}}<br/>
    <a href="{% url 'atlas:new_uploads' %}">Upload more dicoms</a><br/>
    {% if not case %}
        <div class="alert alert-info" role="alert">
            Series imported from here will be orphaned (not associated with a case). <br/>It is usually better to <a href="{% url 'atlas:case_create' %}">create a case</a> first and then import directly into the case.
        </div>
    {% endif %}

    Click to select cases to import. If no series are selected all will be selected/imported.<br/>


    {% if series_list %}
        <ul id="series-list">
            {% for series, n, tags, date in series_list %}
                <li>
                    <span _="
                             on click toggle .selected on me.closest('li')
                             then set i to the first <input/> in me
                             then set i.checked to not i.checked" >
                        Uploaded: {{date}}<br/>
                        Series: {{series}} [{{n}} images] <br/>
                        {{tags}}
                        <input class="hidden" type="checkbox" name="selection" value="{{ series }}">
                    </span>
                    <span class="series-block-popup-link">
                        <a href="#"
                           onclick="return window.create_popup_window('/atlas/uploads/series_id/{{series}}', 'Series')">Popup</a>
                    </span>
                </li>
            {% endfor %}
        </ul>

        {% if case %}
            <p>Importing into case: <a href='{% url "atlas:case_detail" case.pk %}'>{{case}}</a></p>
        {% endif %}
        <details><summary>Upload settings</summary>
            <form>
                <div>
                    <fieldset><legend>Select how series should be ordered when uploaded</legend>
                        <div class="helptext">
                            This will affect how series are displayed when viewing with the built in site viewer. By default when exporting from Insight the order is not maintained so you should choose to order either by slice location or instance number.<br/>
                            If you are not sure, leave this as the default.
                        </div>
                        <div>
                            <input type="radio" id="order-series-slice-location" value="order-series-slice-location" name="order-series" checked>
                            <label for="order-series-slice-location">Order series by slice location</label><br/>
                        </div>
                        <div>
                            <input type="radio" id="order-series-instance-number" value="order-series-instance-number" name="order-series" >
                            <label for="order-series-instance-number">Order series by instance number</label><br/>
                        </div>
                        <div>
                            <input type="radio" id="order-series-none" value="order-series-none" name="order-series" >
                            <label for="order-series-none">None</label><br/>
                        </div>
                    </fieldset>
                </div>
            </form>
        </details>

        <button id="delete-uploads-button"
                hx-post="{% url 'api-1:clear_dicoms' %}"
                hx-include="[name='selection']"
                hx-confirm="This will clear selected uploads, Continue?"
                title="Deleted selected uploads"
        >Delete Uploads</button>

        <button id="import-dicoms-sequential-button"
                type="button"
                class="btn btn-primary"
        >Import {% if case %}into case{% endif %} (one at a time)</button>

        <div id="import-status"></div>

        <div class="indicator"><div class="loader"></div>Loading...</div>
        <div id="import-status"></div>

        <div class="imported">

        </div>
    {% else %}
        No uploads awaiting importing have been found.

    {% endif %}

    <p><a href="{% url 'atlas:series_view' %}?case=null&sort=-modified_date">View orphan series</a></p>

    <script>
        const importButton = document.getElementById('import-dicoms-sequential-button');
        if (importButton) {
            document.getElementById('import-dicoms-sequential-button').addEventListener('click', async function() {
                const checkboxes = Array.from(document.querySelectorAll('input[name="selection"]:checked'));
                const allCheckboxes = Array.from(document.querySelectorAll('input[name="selection"]'));
    // Only include checkboxes that are not disabled (i.e., not already imported)
                const selectableCheckboxes = allCheckboxes.filter(cb => !cb.disabled);
                const toImport = checkboxes.length
                    ? checkboxes.filter(cb => !cb.disabled)
                    : selectableCheckboxes;
                if (toImport.length === 0) {
                    alert("Please select at least one series to import (not already imported).");
                    return;
                }
                const statusDiv = document.getElementById('import-status');
                statusDiv.innerHTML = '';
                const orderSeries = document.querySelector('input[name="order-series"]:checked').value;
                const csrfToken = '{{ csrf_token }}';
                {% if case %}
                    const importUrl = "{% url 'api-1:import_dicoms_case' case.id %}";
                {% else %}
                    const importUrl = "{% url 'api-1:import_dicoms' %}";
                {% endif %}
                for (let i = 0; i < toImport.length; i++) {
                    const seriesId = toImport[i].value;
                    statusDiv.innerHTML += `<div id="import-status-${seriesId}">Importing series ${seriesId}...</div>`;
                    try {
                        const response = await fetch(importUrl, {
                            method: "POST",
                            headers: {
                                "Content-Type": "application/x-www-form-urlencoded",
                                "X-CSRFToken": csrfToken,
                            },
                            body: `selection=${encodeURIComponent(seriesId)}&order-series=${encodeURIComponent(orderSeries)}`
                        });
                        const text = await response.text();
                        document.getElementById(`import-status-${seriesId}`).innerHTML = `Series ${seriesId}: ${text}`;
            // Mark as imported in the UI and make unselectable
                        const li = document.querySelector(`#series-list input[value="${seriesId}"]`)?.closest('li');
                        if (li && !li.classList.contains('imported')) {
                            li.classList.add('imported');
                // Add badge if not already present
                            if (!li.querySelector('.badge.bg-success')) {
                                const badge = document.createElement('span');
                                badge.className = 'badge bg-success ms-2';
                                badge.textContent = 'Imported';
                                li.appendChild(badge);
                            }
                // Disable checkbox and prevent further selection
                            const checkbox = li.querySelector('input[name="selection"]');
                            if (checkbox) {
                                checkbox.disabled = true;
                                checkbox.checked = false;
                            }
                // Remove click handler for selection
                            li.querySelector('span').onclick = null;
                            li.style.pointerEvents = "none";
                            li.style.opacity = "0.7";
                        }
                    } catch (e) {
                        document.getElementById(`import-status-${seriesId}`).innerHTML = `Series ${seriesId}: <span style="color:red;">Failed</span>`;
                    }
                }
                statusDiv.innerHTML += "<div>All done.</div>";
            });
        }
    </script>

{% endblock %}


{% block css %}
    <style>
        .indicator {
            display: none;
        }

        .indicator.htmx-request {
            display: block;
        }

        .loader {
            width: 50px;
            aspect-ratio: 1;
            display: grid;
        }
        .loader::before,
        .loader::after {
            content:"";
            grid-area: 1/1;
            --c:no-repeat radial-gradient(farthest-side,#25b09b 92%,#0000);
            background:
                        var(--c) 50%  0,
                        var(--c) 50%  100%,
                        var(--c) 100% 50%,
                        var(--c) 0    50%;
            background-size: 12px 12px;
            animation: l12 1s infinite;
        }
        .loader::before {
            margin: 4px;
            filter: hue-rotate(45deg);
            background-size: 8px 8px;
            animation-timing-function: linear
        }

        @keyframes l12 {
            100%{transform: rotate(.5turn)}
        }

        #series-list {
            user-select: none;
            cursor: pointer;
        }

        #series-list li {
        }
        #series-list .selected {
            color: white;
            border: 1px solid #52057b;
            user-select: none;
            margin: -1px;

        }
        .series-block-popup-link {
            float: right;
        }
        #series-list li.imported {
            border-color: #e6ffe6;
            opacity: 0.7;
        }
    </style>

{% endblock css %}
