{% load i18n %}
{% load common_filters %}


{% comment %}
<!--
  Copyright (C) 2011 University of Dundee & Open Microscopy Environment.
  All rights reserved.

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU Affero General Public License as
  published by the Free Software Foundation, either version 3 of the
  License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
-->
{% endcomment %}


    <link rel="stylesheet" type="text/css" href="{% static "webgateway/css/ome.plateview.css"|add:url_suffix %}" media="all" />

    <script type="text/javascript">

        $(document).ready(function() {

            // Drag to resize #wellImagesContainer bottom panel
            $(".verticalDragHandle").draggable({ axis: "y" })
            .on("dragstart", function(event, ui) {
                var wellImgs_h = $("#wellImagesContainer").height();
                $(this).data({'dragstart': ui.offset.top, 'wellImgs_h': wellImgs_h});
            })
            .on("drag", function(event, ui) {
                var dy = ui.offset.top - $(this).data('dragstart');
                var newH = $(this).data('wellImgs_h') - dy;
                $("#wellImagesContainer").css('height', newH + 'px');
                $("#spwContainer").css('bottom', newH + 'px');
            })
            .on("dragstop", function(event, ui) {
                // Save the current size
                var dy = ui.offset.top - $(this).data('dragstart');
                var newH = $(this).data('wellImgs_h') - dy;
                $('body').data('well_images_panel_height', newH);
            });
            // If height has previously been set, apply this...
            var newH = $('body').data('well_images_panel_height') || 150;
            $("#wellImagesContainer").css('height', newH + 'px');
            $("#spwContainer").css('bottom', newH + 'px');
            $("#wellImagesDragHandle").css('bottom', (newH + 7) + 'px');

            // Resize SPW thumbnails
            var spw_thumb_size = $('body').data('spw_thumb_size') || 64;
            $("#thumb_size_slider").slider({
                max: 130,
                min: 10,
                value: spw_thumb_size,
                slide: function(event, ui) {
                    // find current centre (as ratio of grid width/height)
                    let $spw = $("#spw");
                    let $table = $("#spw>table");
                    let tableW = $spw.width() / 2;
                    let tableH = $spw.height() / 2;
                    let cx = ($spw.scrollLeft() + tableW) / $table.width();
                    let cy = ($spw.scrollTop() + tableH) / $table.height();
                    // resize
                    wpv.setSpwThumbSize(ui.value);
                    // scroll to recentre
                    $spw.scrollLeft((cx * $table.width()) - tableW);
                    $spw.scrollTop((cx * $table.height()) - tableH);
                },
                stop: function(event, ui) {
                    $('body').data('spw_thumb_size', ui.value);
                }
            });
            // Resize Images in Well
            var well_images_size = $('body').data('well_images_size') || 64;
            var prev_well_images_size = well_images_size;
            $("#wellImages").addClass('wellSize' + well_images_size);
            $("#wellImages_size_slider").slider({
                max: 130,
                min: 30,
                value: well_images_size,
                slide: function(event, ui) {
                    $("#wellImages").removeClass('wellSize' + prev_well_images_size).addClass('wellSize' + ui.value);
                    prev_well_images_size = ui.value;
                },
                stop: function(event, ui) {
                    $('body').data('well_images_size', ui.value);
                }
            });

            // Trigger Well Images selected (to update right panel)
            var triggerWellImagesSelection = function() {
                var selected_ids = [];
                $("#wellImages li.ui-selected").each(function(){
                    selected_ids.push(this.getAttribute('data-imageId'));
                });
                // This may be redundant if selection change came from birds eye component
                wellBirdsEye.setSelected(selected_ids);

                // trigger right panel update etc
                var selected_objs = selected_ids.map(function(iid){
                    return {id: 'image-' + iid};
                })
                $("body")
                    .data("selected_objects.ome", selected_objs)
                    .trigger("selection_change.ome");
            };
            // Handle click on Wellsample Images
            $( '#wellImages' ).on( "click", "a", function(event) {
                event.preventDefault();
                // Update 'ui-selected' on images, handling shift-click etc
                var $a = $(event.target).parent();
                OME.handleClickSelection(event, $a, "#wellImages .wellSize");
                triggerWellImagesSelection();
                return false;
            });
            // Listen for double-clicks to open image viewer
            $( "#wellImages").on("dblclick", "a", function() {
                window.open($(this).prop('href'), '_blank');
            });
            // Drag selection on WellSample images
            $('#wellImages').selectable({
                filter: 'li',
                distance: 2,
                stop: function(){
                    triggerWellImagesSelection();
                }
            });

            var syncTreeSelection = function(selected, idx, perms) {
                // De-select 'Run' from tree, silent 'true' so we don't trigger clear of centre panel
                var datatree = $.jstree.reference('#dataTree');
                // Update the buttons in the jstree as if nothing selected.
                if (buttonsShowHide) {
                    buttonsShowHide([], datatree);
                }
                // Calls to ome.webclient.actions.js
                OME.well_selection_changed(selected, idx, perms);
            };

            var staticurl = WEBCLIENT.URLS.static_webgateway;
            var wpv = $.WeblitzPlateview($('#spw'),
                { baseurl: '{{ baseurl }}',
                  width: spw_thumb_size,
                  staticurl: staticurl,
                  useParentPrefix: false,
                  thumbnailsBatch: {{ thumbnails_batch|default:50|json_dumps|safe }},
                  defaultThumb: "{% static 'webgateway/img/image128.png' %}"
                 });
            var $selected;
            // delegated click and dblclick handlers for wells
            $( '#spw' ).on( "click", "td.well img", function(event) {
                OME.handleClickSelection(event, undefined, "#spw td.well img");
                var $selected = $('td.ui-selected', wpv.self);
                syncTreeSelection($selected, {{ index }}, '{{ manager.getPermsCss }}');
                showImagesInWell();
            });
            $( '#spw' ).on( "dblclick", "td.well img", function(event) {
                var url = "{% url 'web_image_viewer' 0 %}".replace('/0/', "/"+$(this).attr('id').split("-")[1]+"/" );
                window.open(url, '_blank');
            });

            wpv.self.selectable({
                filter: 'td.well',
                distance: 2,
                stop: function(){
                    var $selected = $('td.ui-selected', this);
                    syncTreeSelection($selected, {{ index }}, '{{ manager.getPermsCss }}');
                    showImagesInWell();
                },
                start: function(){
                }
            });
            {% if select_wells %}
                wpv.self.on('_resetLoaded', function(){
                    var sel_well_ids = [{{ select_wells }}],
                        well_id, $well
                        selected_wells = $("");
                    for (var s=0;s<sel_well_ids.length;s++){
                        well_id = sel_well_ids[s];
                        if (typeof well_id === "number") {
                            $well = $("#well-"+well_id);
                            if ($well.length > 0) {
                                selected_wells = selected_wells.add($well);
                            }
                        }
                    }
                    if (selected_wells.length > 0) {
                        OME.handleClickSelection(undefined, $("img", selected_wells), "#spw td.well img");
                        $selected = $('td.ui-selected', wpv.self);
                        syncTreeSelection($selected, {{ index }}, '{{ manager.getPermsCss }}');
                        var show = OME.getURLParameter('show');
                        var imageIds = [];
                        if (show) {
                            // handle multiple images: show=image-1|image-2
                            show = show.split('image-');
                            if (show.length > 1) {
                                imageIds = show.slice(1).map(function(iid){return parseInt(iid)});
                            }
                        }
                        showImagesInWell(imageIds);
                    }

                    var selection = $("td.ui-selected").first();
                    if (typeof selection !== 'undefined' && selection.length > 0) {
                        var spwContainer = $("#spwContainer");
                        var fillSpace = $("#spw");
                        fillSpace.scrollTop(selection.position().top - (spwContainer.height() / 2) + selection.height() / 2);
                        fillSpace.scrollLeft(selection.position().left - (spwContainer.width() / 2) + selection.width() / 2);
                    }
                });
            {% endif %}

            // Kick-off loading...
            wpv.load({{ manager.getPlateId }}, {{ index }}, {{ acquisition }});


            // Lower panel.....

            // Wrap images to a fixed number per row...
            $("#imagesPerRow").on('change', function(){
                var imagesPerRow = parseInt(this.value, 10);
                var $lists = $("#wellImages ul");
                // Remove any existing <br>
                $("br", $lists).remove();
                if (isNaN(imagesPerRow)) return;
                // Add <br> after each nth image
                $("li:nth-child(" + imagesPerRow + "n)", $lists).after('<br>');
            });

            // Callback for the spatial birds eye component
            var selectImages = function(imageIds) {
                $("#wellImages li").removeClass('ui-selected');
                imageIds.forEach(function(iid){
                    $("#wellImages li[data-imageId=" + iid + "]").addClass('ui-selected');
                });
                triggerWellImagesSelection();
            }

            var wellBirdsEye = OME.WellBirdsEye({callback: selectImages});
            var showImagesInWell = function(selectImageIds) {
                var $table = $("#wellImages table");
                var $selected = $('td.ui-selected', wpv.self);
                $table.empty();
                wellBirdsEye.clear();
                $selected.each(function(i, w){
                    var wellId = w.id.split('-')[1];
                    var label = $(w).children('.wellLabel').text();
                    var labelHtml = "<td class='wellImagesLabel'><h1>" + label + "</h1></td>";
                    // create placeholders for each Well
                    $table.append("<tr id='wellImages-" + wellId + "'>" + labelHtml + "</tr>");
                    var url = "{% url 'webgateway' %}well/" + wellId + "/children/";
                    {% if acquisition %}
                        url += '?run={{ acquisition }}'
                    {% endif %}
                    $.getJSON(url, function(data){
                        wellBirdsEye.addWell(data);
                        var imagesPerRow = parseInt($("#imagesPerRow").val(), 10);
                        var html = data.reduce(function(html, w, idx){
                            var cls = '';
                            if (selectImageIds && selectImageIds.indexOf(w.id) > -1) {
                                cls = 'class="ui-selected"';
                            }
                            html += '<li ' + cls + ' title="' + w.name.escapeHTML() + '" data-imageId="' + w.id + '">';
                            html += '<a href="{% url 'webindex' %}img_detail/' + w.id + '/">';
                            html += '<div class="wellSize"><img /></div>';
                            html += '</a></li>';
                            if (!isNaN(imagesPerRow) && (idx+1)%imagesPerRow === 0) {
                                html += '<br>';
                            }
                            return html;
                        }, "");
                        // We use .html() instead of .append() so double-clicks don't give duplicate html
                        $('#wellImages-' + wellId).html(labelHtml + "<td><ul>" + html + "</ul></td>");
                        if (selectImageIds && selectImageIds.length > 0) {
                            triggerWellImagesSelection();
                        }
                        var iids = data.map(function(i){
                            return i.id;
                        });
                        // Load thumbnails
                        var thumbnailsBatch = {{ thumbnails_batch|default:50|json_dumps|safe }};
                        OME.load_thumbnails("{% url 'get_thumbnails_json' %}",
                                            iids, thumbnailsBatch,
                                            "{% static 'webgateway/img/image128.png' %}"
                        );
                    });
                });
            }
        });

    </script>


    <!--content-->
<!-- We add/remove class .showWellImages to #content_details expose #wellImages panel -->
<div class='fillSpace' style="top: 0px; height: 29px">
    <div id="fields">
        <form action="" method="POST" class="align_left">
        <table>
          <tbody>
            {% for field in form_well_index %}
            <tr><th>{{ field.label_tag }}</th><td class="input">{{ field }}</td><td>{% if field.errors %}{{ field.errors }}{% endif %}{{ field.help_text|safe }}</td></tr>
            {% endfor %}
            <div id="well_index" style="display:none">{{ index }}</div>
          </tbody>
        </table>
        </form>
        <div id="toolbar" class="toolbar_noborder">
        </div>
    </div>
</div>
<div id="spwContainer" class='fillSpace' style="top: 29px; bottom: 150px">

    <!-- Scrollable container for spw -->
    <div id="spw" style='position: absolute; left: 0; right: 0; top: 0; bottom: 25px'></div>
    <div class='fillSpace' style='bottom: 0; height: 25px; border-top: solid 1px #ddd; background: #EFF1F4' >
        <!-- Slider -->
        <div style="position: absolute; right: 10px; bottom: 0; width: 200px; height: 25px">
            <span class="zoomLabel">Zoom:</span>
            <div id="thumb_size_slider" class="thumb_size_slider" title="Zoom Plate"></div>
        </div>
    </div>
</div>
<div id="wellImagesDragHandle" class='fillSpace' style="bottom: 150px; overflow: visible">
    <div class="verticalDragHandle"></div>
</div>
<div id="wellImagesContainer" class="well-fields wellImages fillSpace">
    <div class="well-fields__toolbar toolbarBg">
        <div class="well-fields__toolbar-tools--left">
            <div class="wrap-images-tool">
                <span class="text--medium">wrap</span>
                <input class="wrap-images-tool__input" id="imagesPerRow" type="number" min="0" max="99"/>
                <span class="text--medium">images per row</span>
            </div>
        </div>
        <div class="well-fields__toolbar-title">
            <span class="text--medium">Fields from well</span>
        </div>
    </div>
    <!-- Scrollable container for wellImages -->
    <div id="wellImages" class="well-fields__images fillSpace">
        <table style="width: 100%"></table>
    </div>
    <div class='fillSpace' style='bottom: 0; height: 25px; border-top: solid 1px #ddd; background: #EFF1F4' >
        <!-- Slider -->
        <div style="position: absolute; right: 10px; bottom: 0px; width: 200px; height: 25px">
            <span class="zoomLabel">Zoom:</span>
            <div id="wellImages_size_slider" class="thumb_size_slider" title="Zoom Plate"></div>
        </div>
    </div>
</div>