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

{% block content %}
    <details class="help-text">
        <summary><i class="bi bi-info-circle"></i> Help</summary>
        <p>This set up is designed to allow you to project/share cases in a seperate window whilst controlling/tracking their display from this page.</p>
        <p>First you will need to open the linked viewer window by clicking the 'Open Viewer' button. This will open a new window/tab with the viewer in it. You will probably need to detach this from your current window.</p>
        <p>If you are sharing the window you can maximise the screen area by hiding the tab/bookmark bar and the address bar. In Microsoft Edge this can be done by installing as an app, in Chrome you can use an extension such as <a href='https://chromewebstore.google.com/detail/ncppfjladdkdaemaghochfikpmghbcpc'>Open-as-Popup</a>.</p>
        <p>Click on the 'Load' button to open the case in a the linked window. Loading subsequent cases/series will replace the first case in the window.</p>
        <p>It is also possible to open a single series by clicking on the 'Load' button next to the individual series.</p>
        <p>Once opened the case details will be show on the right hand side of the page.</p>

        <div class="mb-2">
            <button id="toggle-load-mode" class="btn btn-secondary">Switch to Load OHIF</button>
            <button id="toggle-edit-mode" class="btn btn-warning ms-2">Enable Edit Mode</button>
        </div>
    </details>
    <div class="container">
        <div class="row">
            <div class="col-sm">
                <h3>Cases</h3>
                <button id="open-viewer" >Open Viewer OHIF</button>
                <button id="open-viewer-local" >Open Viewer Local</button>
                <button id="view-series" class="text-dark border-dark" >Toggle series</button>
                <ol id="" class="sortable">
                    {% for casedetail in casedetails %}
                        {% with case=casedetail.case %}
                            <li data-question_pk={{case.pk}}>
                                <div class="case-item" data-title="{{case.title}}" data-case={{case.pk}} data-casejson='{{case.get_viva_details_json}}' data-images='{{case.get_series_images_nested}}' data-viewerstate={{casedetail.default_viewerstate_string}}>
                                    Case {{forloop.counter}}: {{case.title}} &nbsp;
                                    <button class="open-case no-padding"  data-target="/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% url 'atlas:case_dicom_json' case.pk %}" data-type="case">Load OHIF</button>
                                    <button class="open-case-local no-padding"  data-target=case.pk data-type="case">Load</button>
                                    <!-- Edit mode link for case -->
                                    <button class="view-link-case btn btn-outline-primary btn-sm ms-2" style="display:none;">
                                        <a href="{% url 'atlas:case_detail' case.pk %}" style="color: inherit; text-decoration: none;">View Case</a>
                                    </button>
                                    <button class="edit-link-case btn btn-outline-warning btn-sm ms-2" style="display:none;">
                                        <a href="{% url 'atlas:case_update' case.pk %}?next={{ request.get_full_path|urlencode }}" style="color: inherit; text-decoration: none;">Edit Case</a>
                                    </button>
                                    <br />
                                    <div class="pre-whitespace multi-image-block">
                                        <details class="series-detail"><summary>Series:</summary>
                                            {% for series in case.series.all %}
                                                <span class="series-block">
                                                    <span>
                                                        <span class="series-block-series-number">Series {{ forloop.counter }}:</span><br>
                                                        test
                                                        {{series.get_block}}
                                                        <br />
                                                        <button class="open-series no-padding text-secondary border-secondary" data-type="series" data-series={{forloop.counter}} data-case={{case.pk}} data-target="/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% url 'atlas:series_dicom_json' series.pk %}">
                                                            Load
                                                        </button>
                                                        <button class="open-series-local no-padding text-secondary border-secondary"
                                                                data-type="series"
                                                                data-series="{{ forloop.counter }}"
                                                                data-case="{{ case.pk }}"
                                                                data-target="{{ series.pk }}">
                                                            Load
                                                        </button>
                                    <!-- Edit mode link for series -->
                                                        <button class="edit-link-series btn btn-outline-warning btn-sm ms-2" style="display:none;">
                                                            <a href="{% url 'atlas:series_update' series.pk %}" style="color: inherit; text-decoration: none;">Edit Series</a>
                                                        </button>
                                                        <br>
                                                    </span>
                                                </span>
                                            {% endfor %}
                                        </details>
                                    </div>
                                    {# Hidden per-case question snippet to inject when case is loaded #}
                                    <div class="question-block-snippet" style="display:none;">
                                        {% include 'atlas/partials/collection_question_block.html' with casedetail=casedetail %}
                                    </div>
                                    {# Attached resources for this case: allow loading into the shared viewer #}
                                    {% if case.caseresource_set.exists %}
                                        <div class="mt-2">
                                            <strong>Resources:</strong>
                                            <div class="d-flex flex-column gap-1">
                                                {% for cr in case.caseresource_set.all %}
                                                    {% with res=cr.resource %}
                                                        <div>
                                                            <span class="me-2">{{ res.name }}</span>
                                                            <button class="open-resource btn btn-sm btn-outline-primary ms-1" data-src="{% if res.file %}{{ res.file.url }}{% else %}{{ res.url }}{% endif %}" data-title="{{ res.name|escapejs }}">Load</button>
                                                        </div>
                                                    {% endwith %}
                                                {% endfor %}
                                            </div>
                                        </div>
                                    {% endif %}
                                    {% if case.display_sets.all %}
                                        <details class="displayset-detail"><summary>Display Sets:</summary>
                                            {% for ds in case.display_sets.all %}
                                                <div class="displayset-block">
                                                    <span>
                                                        <b>{{ ds.name }}</b>
                                                        {% if ds.description %}
                                                            <span class="text-muted">({{ ds.description }})</span>
                                                        {% endif %}
                                                        <button class="open-displayset no-padding text-secondary border-secondary"
                                                                data-type="displayset"
                                                                data-displayset="{{ ds.pk }}"
                                                                data-case="{{ case.pk }}"
                                                                data-title="{{ ds.name }}"
                                                                data-casejson='{{case.get_viva_details_json}}'
                                                                data-images='{{case.get_series_images_nested}}'
                                                                data-viewerstate={{ds.viewerstate_string}}
                                                                data-annotations='{{ds.annotations_string}}'
                                                        >
                                                            Load Display Set
                                                        </button>
                                                        <!-- Edit mode link for display set -->
                                                        <button class="edit-link-displayset btn btn-outline-warning btn-sm ms-2" style="display:none;">
                                                            <a href="{% url 'atlas:case_displaysets' case.pk %}?displayset={{ ds.pk }}&edit=true" style="color: inherit; text-decoration: none;">Edit Display Set</a>
                                                        </button>
                                                    </span>
                                                </div>
                                            {% empty %}
                                                <span class="text-muted">No display sets for this case.</span>
                                            {% endfor %}
                                        </details>
                                    {% endif %}
                                </div>
                            </li>
                        {% endwith %}
                    {% endfor %}
                </ol>
            </div>
            <div class="col-sm">

                <div class="sticky-top">
                    <h3>Current Case</h3>
                    <div id="case-details">
                        <div id="loading-case">Waiting for case to load in linked window.<br/> If you are seeing this message you probably need to open the viewer window and reload the case.</div>
                        <div id="current-case-title">None</div>
                        <div id="current-case-series"></div>
                        <div id="current-case-history"></div>
                        <div id="current-case-discussion"></div>
                        <div id="current-case-report"></div>
                        <div id="current-case-questions" class="mt-3"></div>
                    </div>
                </div>
            </div>
        </div>
{% endblock %}


{% block js %}
    <script type="text/javascript">
        var win2 = false;
        let editMode = false;

        $(document).ready(function() {
            let loadLocalMode = true;


            // Edit mode toggle
            $('#toggle-edit-mode').click(function() {
                editMode = !editMode;
                if (editMode) {
                    $('.edit-link-case').show();
                    $('.view-link-case').show();
                    $('.edit-link-series').show();
                    $('.edit-link-displayset').show();
                    $(this).text('Disable Edit Mode').removeClass('btn-warning').addClass('btn-danger');
                } else {
                    $('.edit-link-case').hide();
                    $('.view-link-case').hide();
                    $('.edit-link-series').hide();
                    $('.edit-link-displayset').hide();
                    $(this).text('Enable Edit Mode').removeClass('btn-danger').addClass('btn-warning');
                }
            });

    // Update all "Load" buttons to reflect the current mode
            function updateLoadButtons() {
                if (loadLocalMode) {
                    $('.open-case').hide();
                    $('.open-series').hide();
                    $('.open-case-local').show();
                    $('.open-series-local').show();
                    $('#toggle-load-mode').text('Switch to Load OHIF');
                    $("#open-viewer").hide()
                    $("#open-viewer-local").show()
                } else {
                    $('.open-case').show();
                    $('.open-series').show();
                    $('.open-case-local').hide();
                    $('.open-series-local').hide();
                    $("#open-viewer").show()
                    $("#open-viewer-local").hide()
                    $('#toggle-load-mode').text('Switch to Load Local');
                }
            }

    // Initial state: show only normal Load buttons
            updateLoadButtons();

    // Toggle button click handler
            $('#toggle-load-mode').click(function() {
                loadLocalMode = !loadLocalMode;
                updateLoadButtons();
            });

            const bc = new BroadcastChannel("viva_load");
            bc.onmessage = (event) => {
                console.log("message received");
                console.log(event);
                if (event.data.type == "open-complete") {
                    $("#loading-case").hide();
                    $("#open-viewer").removeClass("flash-button");
                    //bc.postMessage({"type": "open-complete", "url" : event.data.url});
                }

                if (event.data.type == "open-complete-local") {
                    $("#loading-case").hide();
                    $("#open-viewer-local").removeClass("flash-button");
                    //bc.postMessage({"type": "open-complete-local"});
                }
            };
            console.log('ready')
            $('.show-collection, .show-case, .show-series').click(function() {
                var url = $(this).data('target');
                console.log('clicked', url)
                $('#case-title').text($(this).data('title'));
                $('#viewer').attr('src', url)
            });
            $('.open-case-local').click(function() {
                let c = this.closest(".case-item");
                console.log('clicked local', c)
                console.log('open local', c.dataset.case)
                casedetails = JSON.parse(c.dataset.casejson);
                let viewerstate = JSON.parse(c.dataset.viewerstate) || {};
                $('#loading-case').show()
                $("#open-viewer-local").addClass("flash-button");
                $('#current-case-title').html("<span class='title'>Case:</span> "+c.dataset.title);
                $("#current-case-history").html("<span class='title'>History:</span> "+casedetails['history']);
                $("#current-case-discussion").html("<span class='title'>Discussion:</span> "+casedetails['discussion']);
                $("#current-case-report").html("<span class='title'>Report:</span> "+casedetails['report']);

                bc.postMessage({"type": "open",
                    "case" : c.dataset.case, "images": c.dataset.images,
                    "viewerstate": viewerstate
                });

                // Inject the per-case question snippet into the current case panel
                try {
                    var snippet = $(c).find('.question-block-snippet').html();
                    $('#current-case-questions').html(snippet || '');
                } catch (e) {
                    console.warn('Unable to inject question snippet', e);
                }

            });
            $('.open-displayset').click(function() {
                let c = this;
                console.log('clicked local', c)
                console.log('open local', c.dataset.case)
                casedetails = JSON.parse(c.dataset.casejson);
                let viewerstate = JSON.parse(c.dataset.viewerstate) || {};
                let annotations = JSON.parse(c.dataset.annotations) || {};
                $('#loading-case').show()
                $("#open-viewer-local").addClass("flash-button");
                $('#current-case-title').html("<span class='title'>Case:</span> "+c.dataset.title);
                $("#current-case-history").html("<span class='title'>History:</span> "+casedetails['history']);
                $("#current-case-discussion").html("<span class='title'>Discussion:</span> "+casedetails['discussion']);
                $("#current-case-report").html("<span class='title'>Report:</span> "+casedetails['report']);

                bc.postMessage({"type": "open",
                    "case" : c.dataset.case, "images": c.dataset.images,
                    "viewerstate": viewerstate,
                    "annotations": annotations
                });

                // Inject the per-case question snippet
                try {
                    var caseItem = $(this).closest('.case-item');
                    var snippet = caseItem.find('.question-block-snippet').html();
                    $('#current-case-questions').html(snippet || '');
                } catch (e) {
                    console.warn('Unable to inject question snippet for displayset', e);
                }

            });
            $('.open-series-local').click(function() {
                let c = $(this).closest(".case-item")[0];
                let seriesNumber = $(this).data('series');
                let seriesPk = $(this).data('target');
                let caseDetails = JSON.parse(c.dataset.casejson);
                let images = JSON.parse(c.dataset.images)[seriesNumber - 1] || [];
                $('#loading-case').show();
                $("#open-viewer-local").addClass("flash-button");
                $('#current-case-title').html("<span class='title'>Case:</span> " + c.dataset.title);
                $('#current-case-series').html("<span class='title'>Series:</span> " + seriesNumber);
                $("#current-case-history").html("<span class='title'>History:</span> " + caseDetails['history']);
                $("#current-case-discussion").html("<span class='title'>Discussion:</span> " + caseDetails['discussion']);
                $("#current-case-report").html("<span class='title'>Report:</span> " + caseDetails['report']);

    // Send only the images for this series
                bc.postMessage({
                    "type": "open",
                    "case": c.dataset.case,
                    "series": seriesPk,
                    "images": JSON.stringify(images),
                });

                // Inject the per-case question snippet
                try {
                    var snippet = $(c).find('.question-block-snippet').html();
                    $('#current-case-questions').html(snippet || '');
                } catch (e) {
                    console.warn('Unable to inject question snippet for series', e);
                }
            });
            $('.open-case, .open-series').click(function() {
                var url = $(this).data('target');
                console.log('clicked', url)


                let c = $(this).closest(".case-item");

                casedetails = c.data('casejson');
                console.log(casedetails);

                $('#loading-case').show()
                $("#open-viewer").addClass("flash-button");
                $('#current-case-title').html("<span class='title'>Case:</span> "+c.data('title'));
                $("#current-case-history").html("<span class='title'>History:</span> "+casedetails['history']);
                $("#current-case-discussion").html("<span class='title'>Discussion:</span> "+casedetails['discussion']);
                $("#current-case-report").html("<span class='title'>Report:</span> "+casedetails['report']);

                console.log($(this).data('type'))
                if ($(this).data('type') == 'case') {
                    $('#current-case-series').html("<span class='title'>Series:</span> All");
                } else {
                    $('#current-case-series').html("<span class='title'>Series:</span> " + $(this).data('series'));
                }
                bc.postMessage({"type": "open", "url" : url});
                // Inject question snippet for this case
                try {
                    var caseItem = $(this).closest('.case-item');
                    var snippet = caseItem.find('.question-block-snippet').html();
                    $('#current-case-questions').html(snippet || '');
                } catch (e) {
                    console.warn('Unable to inject question snippet', e);
                }
                //if (win2 == false || win2.closed) {
                //    win2 = openSecondaryWindow(url);
                //    console.log('opened', win2)
                //} else {
                //    win2.location.href = url
                //}
            //win2 = openSecondaryWindow(url);
            })
            // Load resource into linked viewer
            $('.open-resource').click(function() {
                var src = $(this).data('src');
                var title = $(this).data('title') || 'Resource';
                $('#loading-case').show();
                $("#open-viewer-local").addClass("flash-button");
                $('#current-case-title').html("<span class='title'>Resource:</span> "+title);
                $('#current-case-history').html('');
                $('#current-case-discussion').html('');
                $('#current-case-report').html('');

                bc.postMessage({"type": "open", "url": src});
            });
            $('.send-message').click(function() {
                var url = $(this).data('target');
                bc.postMessage(url);
            })
            $('#open-viewer').click(function() {
                $("#open-viewer").removeClass("flash-button");
                openSecondaryWindow("{% url 'atlas:collection_viewer' %}");
                //bc.postMessage(url);
            })
            $('#open-viewer-local').click(function() {
                $("#open-viewer-local").removeClass("flash-button");
                openSecondaryWindow("{% url 'atlas:collection_viewer_local' %}");
                //bc.postMessage(url);
            })
            $('#view-series').click(function() {
                $(".series-detail").attr("open", (_, attr) => !attr);
                //document.getElementsByClassName("series-detail").toggleAttribute("open");
                //bc.postMessage(url);
            })

        });
        function openSecondaryWindow(url) {
   //return win2 = window.open(url,'secondary','width=300,height=100');
            return win2 = window.open(
                url,
                'secondary',
                'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=1200,height=800'
            );
        }

    </script>

    {{ form.media }}
{% endblock %}

{% block css %}

    <style type="text/css">
        #loading-case {
            display: none;
            color: red;
        }
        @keyframes glowing {
            0% {
                box-shadow: 0 0 20px #a600ff;
            }
            50% {
                box-shadow: 0 0 40px #52057b;
            }
            100% {
                box-shadow: 0 0 20px #a600ff;
            }
        }
        .flash-button {
            animation: glowing 1300ms infinite;
        }

        #case-details {
            padding-bottom: 20px;
        }

        .title {
            font-weight: bold;
        }

        .edit-link-case, .edit-link-series, .edit-link-displayset {
            vertical-align: middle;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/@json-editor/json-editor@latest/dist/jsoneditor.min.js"></script>
    <script src="/static/django_jsonforms/jsoneditor_init.js"></script>
{% endblock css %}