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

{% load static %}

{% block js %}
    <!--<script type="text/javascript" src="/admin/jsi18n/"></script>-->

    <script type="text/javascript">
        let csrf_token = "{{csrf_token}}";
        let hash_url = false;
        document.addEventListener('drop', function (e) { e.preventDefault(); }, false);

        $(document).ready(function () {
            $("#add_examination").appendTo($("label[for='id_examination']"));

            dropContainer = document.getElementById("drop-container");

            dropContainer.ondragover = function (evt) {
                evt.preventDefault();
                evt.stopPropagation();
            };

            dropContainer.ondragenter = function (evt) {
                console.log("ENTER")
                console.log(evt)
                $(evt.target).addClass("drop-target-active")
                evt.preventDefault();
                evt.stopPropagation();
            };

            dropContainer.ondragleave = function (evt) {
                console.log("ENTER")
                console.log(evt)
                $(evt.target).removeClass("drop-target-active")
                evt.preventDefault();
                evt.stopPropagation();
            };

            dropContainer.ondrop = function (evt) {
                $(evt.target).removeClass("drop-target-active");

                file_drop_number = evt.dataTransfer.files.length;

                if (file_drop_number < 1) {
                    toastr.warning(`Drop failed (no files), try again.`);
                } else {
                    toastr.info(`Loading ${file_drop_number} dropped image(s).`);
                }

                // Get all input elements
                inputs = extendInputs("atlas-form", file_drop_number);

                console.log("drop inputs", inputs, evt);


                // Loop through each dropped file and try to assign to an
                // input element
                [...evt.dataTransfer.files].forEach((f) => {
                    feedback = false;
                    if (evt.target.id == "feedback-drop-target") {
                        feedback = true;
                    }
                    addFile(f, feedback)
                })

                evt.preventDefault();
                evt.stopPropagation();
            };
            //dropContainer.ondrop = function (evt) {
            //    $(evt.target).removeClass("drop-target-active");


            //    if (evt.dataTransfer.files.length < 1) {
            //        toastr.warning(`Drop failed :( try again?`);
            //    } else {
            //        toastr.info(`Adding ${evt.dataTransfer.files.length} files.`);
            //    }

            //    // Get all input elements
            //    inputs = $("#atlas-form input[type=file][id^=id_images-]");
            //    //fileInput = document.getElementById("id_images-0-image");

            //    // Make sure we have enough input targets
            //    input_diff = (evt.dataTransfer.files.length - inputs.length)

            //    if (input_diff > 0) {
            //        for (let j = 0; j < input_diff; j++) {
            //            add_input_form()
            //        }

            //        // Need to make sure we include the new ones...
            //        inputs = $("#atlas-form input[type=file][id^=id_images-]");
            //    }

            //    // Loop through each dropped file and try to assign to an
            //    // input element
            //    [...evt.dataTransfer.files].forEach((f) => {
            //        let dT = new DataTransfer();
            //        dT.clearData();
            //        dT.items.add(f);
            //        for (let i = 0; i < inputs.length; i++) {
            //            el = inputs.get(i)

            //            if (el.files.length == 0) {
            //                el.files = dT.files;
            //                //ocr(el)

            //                return false
            //            }
            //        }
            //    })

            //    // // If you want to use some of the dropped files
            //    // const dT = new DataTransfer();
            //    // dT.items.add(evt.dataTransfer.files[0]);
            //    // dT.items.add(evt.dataTransfer.files[3]);
            //    // fileInput.files = dT.files;

            //    loadDicomViewerAndFileImages();

            //    evt.preventDefault();
            //    evt.stopPropagation();
            //};


            $('#add_more_images').click(() => { add_input_form() });

            $("input[type=file]").on('change', input_change);



            sortable('.sortable');
            sortable('.sortable')[0].addEventListener('sortupdate', function (e) {
                /*

            This event is triggered when the user stops sorting and the DOM position has not yet changed.

            e.detail.item - {HTMLElement} dragged element

            Origin Container Data
            e.detail.origin.index - {Integer} Index of the element within Sortable Items Only
            e.detail.origin.elementIndex - {Integer} Index of the element in all elements in the Sortable Container
            e.detail.origin.container - {HTMLElement} Sortable Container that element was moved out of (or copied from)
            */
                //updateImagePositions();

                $(".temp-thumb").remove()
                loadDicomViewer();
            });
        });



        async function loadDicomViewerAndFileImages(callback) {
            $("#single-dicom-viewer").empty()
            //images = []
            //Function that returns a promise to read the file
            const reader = (file) => {
                return new Promise((resolve, reject) => {
                    const fileReader = new FileReader();
                    fileReader.onload = () => resolve(fileReader);
                    fileReader.readAsDataURL(file);
                });
            }

            const readFile = (file, el) => {
                reader(file).then(reader => {
                    console.log("hello", file, el, image)
                    //if ($("#id_examination").find(":selected")[0].dataset.select2Id == "2") {
                    //    var byteArray = new Uint8Array(reader.result);
                    //    console.log("etrxact", reader)
                    //    extractDicomStudyDescription(byteArray);
                    //}
                    var image = new Image();
                    image.height = 100;
                    image.title = file.name;
                    image.src = reader.result;
                    image.className = "temp-thumb";
                    console.log("read", el);
                    $(el).parent().parent().prepend(image);
                    //images.push(reader.result);
                    loadViewer(images);

                });
            }

            const dicomReader = (file) => {
                return new Promise((resolve, reject) => {
                    const fileReader = new FileReader();
                    fileReader.onload = () => resolve(fileReader);
                    fileReader.readAsArrayBuffer(file);
                });
            }

            const readDicomFile = (file, el) => {
                dicomReader(file).then(reader => {
                    if ($("#id_examination").find(":selected")[0].dataset.select2Id == "2") {
                        var byteArray = new Uint8Array(reader.result);
                        console.log("etrxact", reader)
                        extractDicomDetails(byteArray);
                    }
                });
            }



            file_set = $("#image_form_set input[type=file]");



            file_set.each(async (n, el) => {
                console.log(el);
                if (el.files.length > 0) {
                    filename = el.files[0].name;
                    await readFile(el.files[0], el);
                    readDicomFile(el.files[0]);
                }
            })


            console.log("images from files", images);


        }

//        function loadViewer(images) {
//            //dicomViewer.loadCornerstone($("#single-dicom-viewer"), null, images, annotations);
//            file_set = $("#image_form_set input[type=file]");
//
//            n = 0;
//            for (let i = 0; i < file_set.length; i++) {
//                el = file_set.get(i)
//                if (el.files.length > 0) {
//                    n++;
//                }
//            }
//
//            image_set = $("#image_form_set img");
//            if (n == image_set.length) {
//                const event = new CustomEvent('loadDicomViewer', { "detail": image_set });
//
//                window.dispatchEvent(event);
//                sortable('.sortable');
//                //sortable('.sortable')[0].addEventListener('sortstop', function(e) {
//                updateImagePositions();
//            }
//
//        }

    </script>

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

{% block navigation%}
    {{ block.super }}
    {% if object %}
        {% include "atlas/series_headers.html" %}
    {% endif %}
{% endblock %}
{% block content %}


    <h2>Series Form</h2>
    This form will create a image set that can be associated with a atlas question. If the question has already been created
    it can be linked below.
    <form action="" method="post" enctype="multipart/form-data" id="atlas-form">
        {% csrf_token %}
        <a href="/generic/examination/create" id="add_examination" class="add-popup"
           onclick="return showAddPopup(this);"><img src="{% static 'img/icon-addlink.svg' %}"></a>
        <table>
            {{ form.as_table }}
        </table>

        <h3>Images:</h3>
        <div id="drop-container" class="series-drop">Drop images here (or use the buttons below). Dropping images here will overwrite
            existing images in the series. When drag and dropping make sure to drag the first image or the order will not be
            maintained. Note: dicom images are often not exported in order (although their order can be automatically
            detected once uploaded)
            <div id="single-dicom-viewer" class="dicom-viewer" data-images="" data-annotations=''></div>
            {% comment %} <div id="drop-filenames"></div> {% endcomment %}
        </div>
        <div id="image_form_set" class="sortable">
            {% for form in image_formset %}
                <ul class="no-error image-formset">
                    {{form.non_field_errors}}
                    {{form.errors}}
                    {{ form.as_ul }}
                </ul>
            {% endfor %}
        </div>
        {{ image_formset.management_form }}
        <input type="submit" class="submit-button" value="Submit" name="submit">
    </form>
    <div id="empty_form" style="display:none">
        <ul class='no_error image-formset'>
            {{ image_formset.empty_form.as_ul }}
        </ul>
    </div>
    <div id="images">

    </div>
{% endblock %}
