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

{% load crispy_forms_tags %}

{% block content %}
    {% include "shorts/question_link_header.html" %}
    <p>The viewer shown below can be used to annotate the images. The viewport can be zoomed and paned to highlight the abnormality which can then be indicated with arrows or bounding boxes.</p>

    <div id="single-dicom-viewer" class="dicom-viewer" data-images="{{ question.get_image_url_array }}">
    </div>

    {% if can_edit %}
        {% if editing_finding < 1 %}
            <button id="add-finding-button">Add finding</button>
        {% endif %}
        <button id="reset-viewport-button">Reset viewport</button>
        <div id="finding-form">
            <div class="hide" id="hidden-form">
                <form method="post" id="question_finding_form">
                    {% csrf_token %}
                    {{question_finding_form|crispy}}
                    <input type="submit" value="Submit">
                    <button id="cancel-add-finding-button">Cancel</button>
                </form>
            </div>
        </div>
    {% else %}
        <button id="reset-viewport-button">Reset viewport</button>
    {% endif %}

    <details open>
        <summary>Findings</summary>





        {% for finding in question.findings.all %}
            <div class="finding-box">
                <button class="view-finding-button" data-annotationjson={{finding.annotation_json}}
                        data-viewportjson={{finding.viewport_json}} data-findingid={{finding.id}} data-currentimageid={{finding.current_image_id_index}}>Click to view</button>
                <span class="view-finding-details">
                    Finding(s): {% for f in finding.findings.all %}{{f.get_link}}{% endfor %}<br />
                    Structure(s): {% for s in finding.structures.all %}{{s.get_link}}{% endfor %}<br />
                    Condition(s): {% for s in finding.conditions.all %}{{s.get_link}}{% endfor %}<br />
                    Description: {{finding.description}}<br />

                    {% if request.user.is_superuser %}
                        <span _='on click toggle .hidden on next .extra-details'>+</span>
                        <div class="hidden extra-details">
                            <h4>Annotation JSON</h4>
                    <pre>{{finding.get_pretty_annotation_json}}</pre>
                            <h4>Viewport JSON</h4>
                    <pre>{{finding.get_pretty_viewport_json}}</pre>
                            <h4>Image ID</h4>
                    <pre>{{finding.current_image_id_index}}</pre>
                        </div>
                    {% endif %}
                </span>
                {% if can_edit %}
                    <a href="{% url 'shorts:question_edit_finding' question_id=question.pk finding_pk=finding.pk %}" class="edit-finding-link">Edit</a>
                    <a href="{% url 'shorts:delete_finding' pk=finding.pk %}" class="delete-finding-link">Delete</a>
                {% endif %}
            </div>

        {% endfor %}
    </details>
{% endblock %}



{% block js %}
    
<script>
    $(document).ready(function () {
        $("#add-finding-button").click(() => {
        console.log("add finding button clicked")
            $("#hidden-form").show()
            dicom_element = $(".cornerstone-element").get(0);
            //cornerstoneTools.globalImageIdSpecificToolStateManager.clear(dicom_element);
            //cornerstone.reset(dicom_element);
            ////cornerstone.resize(dicom_element, true);
            $("#add-finding-button").hide()
            //$("#finding-form").empty().append(
            //    $("#hidden-form form").clone()
            //);

        });
        $("#cancel-add-finding-button").click((e) => {
            $("#hidden-form").hide()
            $("#add-finding-button").show()
            e.preventDefault();
        });


        $("#reset-viewport-button").click(() => {
            dicom_element = $(".cornerstone-element").get(0);
            //annotationjson = JSON.parse(e.currentTarget.dataset.annotationjson);
            cornerstoneTools.globalImageIdSpecificToolStateManager.clear(dicom_element);
            cornerstone.reset(dicom_element);
            cornerstone.resize(dicom_element, true);

        });

        $(".view-finding-button").each((n, el) => {
            $(el).click((e) => {
                dicom_element = $(".cornerstone-element").get(0);
                annotationjson = JSON.parse(e.currentTarget.dataset.annotationjson);
                viewport = JSON.parse(e.currentTarget.dataset.viewportjson);
                current_image_id_index = e.currentTarget.dataset.currentimageid;
                console.log(e.currentTarget, current_image_id_index)
                loadAnnotationAndViewportOnElement(annotationjson, viewport, dicom_element, current_image_id_index);


            });

        });


        {% if editing_finding > 0 %}
            $("#hidden-form").show()
            setTimeout(function() {
                $(".view-finding-button[data-findingid={{editing_finding}}]").trigger("click");
            }, 1000)

        {% endif %}
    });

    function loadAnnotationAndViewportOnElement(annotation, viewport, dicom_element, current_image_id_index) {
        cornerstoneTools.globalImageIdSpecificToolStateManager.clear(dicom_element);
        cornerstone.getEnabledElement(dicom_element).viewport = viewport
        cornerstoneTools.globalImageIdSpecificToolStateManager.restoreToolState(
            annotation);
        console.log("annotation", annotation)
        console.log("viewport", viewport)

        //cornerstone.getEnabledElement(dicom_element).toolStateManager.restoreToolState(annotationjson)
        cornerstone.resize(dicom_element);
        console.log("current_image_id_index", current_image_id_index)
        //current_image_id_index = parseInt(current_image_id_index);

        console.log(current_image_id_index, Number.isInteger(current_image_id_index))
        if (Number.isInteger(current_image_id_index)) {
            console.log("loading stack index")
            dicomViewer.loadStackIndex(current_image_id_index, dicom_element);
        } else {
            try {
                console.log("current_image_id_index", current_image_id_index)
                dicomViewer.loadImageById(current_image_id_index, dicom_element);
            } catch (e) {
                console.log(e)
                console.log("loading image by id failed")
                console.log("loading next annotation image")
                dicomViewer.getNextAnnotationImage(dicom_element);
            }
        }

    }

    $(document).on('submit', '#question_finding_form', function (e) {
        dicom_element = $(".cornerstone-element").get(0);
        c = cornerstone.getEnabledElement(dicom_element);
        e.preventDefault();

        $.ajax({
            type: 'POST',
            url: '{% url "shorts:add_finding" %}',
            data: {
                question_finding_id: {{ editing_finding }},
                description: $('#id_description').val(),
                question: {{ question.pk }},
                //annotation_json: JSON.stringify(c.toolStateManager.saveToolState()),
                // This is the stack number
                //current_image_id_index: c.toolStateManager.toolState.stack.data[0].currentImageIdIndex,
                // but we want to use the current image id (so if the stack is reordered it still attaches to the correct image)
                current_image_id_index: c.toolStateManager.toolState.stack.data[0].imageIds[c.toolStateManager.toolState.stack.data[0].currentImageIdIndex],
                annotation_json: JSON.stringify(cornerstoneTools.globalImageIdSpecificToolStateManager
                        .saveToolState()),
                viewport_json: JSON.stringify(c.viewport),
                findings: JSON.stringify($('#finding-form select[name="findings"]').find(":selected")
                        .map((i, el) => {
                            return $(el).val()
                        }).toArray()),
                structures: JSON.stringify($('#finding-form select[name="structures"]').find(
                    ":selected")
                        .map((i, el) => {
                            return $(el).val()
                        }).toArray()),
                conditions: JSON.stringify($('#finding-form select[name="conditions"]').find(
                    ":selected")
                        .map((i, el) => {
                            return $(el).val()
                        }).toArray()),
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                action: 'post'
            },
            success: function (json) {
                $("#finding-form").empty();
                toastr.info('Finding added.');
                location.href='{{question.get_findings_url}}';
            },
            error: function (xhr, errmsg, err) {
                console.log(xhr.status + ": " + xhr
                        .responseText); // provide a bit more info about the error to the console
            }
        });
    });
</script>

{% endblock js %}