{% load i18n %}
{% load common_tags %}
{% 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 %}


    <style>
      /*from omero_image.css*/
      .ui-slider-handle.ui-state-default {
        background: #FEE7D6 none repeat scroll 0 0;
        border: solid #A9A916 1px;
        transition-duration: 0s;
      }
      .rangeslider {
        border: solid #333333 1px;
        margin: 0.2em 1em;
      }
      button.pressed {
        border-style: inset;
      }
      .postit{
        font-size: 0.9em;
      }
      .postit h1 {
        font-size: 2.0em;
      }
      .postit, .postit h1 {
        background-color: #eee;
      }
      .rangewidget input {
        width: 3.1em;
      }

      /* custom */
      #wblitz-channels-box button {
        width: 25px;
        height: 25px;
        float: left;
        position: relative;
        left: -5px;
        text-indent: -1000px; /** hide text **/
        margin: 2px 0;
      }
      img.rdef {
        max-width: 64px;
        max-height: 64px;
        position: relative;
        top: 2px;
        margin-bottom: 3px;
      }
      .thin-margin {
        margin: 3px 0;
      }
      #rdef-active-area td {
        padding: 0 0 4px 0;
      }
      button.rdef {
        border: solid transparent 1px;
        background: transparent;
      }
      button.clicked {
        border-color: blue;
      }
      .rdef .owner {
        color: blue;
      }
      /* histogram svg */
      .line {
        fill: none;
      }
    </style>


    <script type="text/javascript">

        var PLATE_LINKS_URL_999 = '{% url 'webgateway_object_table_query' 'Screen.plateLinks.child.wells' 999 %}';
        var PLATE_WELLS_URL_999 = '{% url 'webgateway_object_table_query' 'Plate.wells' 999 %}';

        $(document).ready(function() {

            // Fix size according to right panel size... NB: this behaviour is also in right_plugin.preview.js
            var vpWidth = $("#right_panel").width() - 50,
              vpHeight = Math.min(vpWidth, $("#preview_tab").height() - 100);
            vpHeight = Math.max(300, vpHeight);
            $("#viewport").css({'width': vpWidth + 'px', 'height': vpHeight + 'px'});


            if (typeof OME === "undefined") {OME = {}}

            // Load the Lookup Tables straight off - need them ASAP
            if (!OME.LUTS) {
              $.getJSON("{% url 'webgateway_listLuts_json' %}", function(data){
                OME.LUTS = data.luts;
                OME.PNG_LUTS = data.png_luts;
              });
            }

            // init viewport
            {% if share and not share.share.isOwned %}
            OME.preview_viewport = $.WeblitzViewport($("#viewport"), "{% url 'webindex' %}{{ share.share.id }}", {'mediaroot': '{{ STATIC_URL }}' } );
            {% else %}
            OME.preview_viewport = $.WeblitzViewport($("#viewport"), "{% url 'webindex' %}", {'mediaroot': '{{ STATIC_URL }}' } );
            {% endif %}

            OME.preview_viewport.bind('imageLoad', _refresh_cb);
            OME.preview_viewport.bind('channelChange', channelChange);
            OME.preview_viewport.bind('imageChange', function(){
              syncChannelsActive(OME.preview_viewport);
            });
            /* Bind image changes */
            OME.preview_viewport.bind('imageChange', function(){
              imageChange(OME.preview_viewport);
            });

            // Create Histogram - displayed when #showhistogram checkbox is checked
            OME.createViewportHistogram(OME.preview_viewport, "#histogram", "#showhistogram", "{% url 'webgateway' %}");

            // Load image
            {% if share and not share.share.isOwned %}
            OME.preview_viewport.load({{ manager.image.id }}, null, location.search);
            {% else %}
            OME.preview_viewport.load({{ manager.image.id }});
            {% endif %}

            // copy and paste refs is in browser via query string,
            // but we also save to session in case of page reload etc
            $("#rdef-copy-btn").on('click', function() {
                copyRdefs(OME.preview_viewport);
            });
            $("#rdef-paste-btn").on('click', function() {
                pasteRdefs(OME.preview_viewport);
            });
            // once image loads, check session via /getImgRDef/ to see if we can paste
            OME.preview_viewport.bind('imageLoad', function() {
              $.getJSON(OME.preview_viewport.viewport_server + "/getImgRDef/",
                function(data){
                    if (data.rdef) {
                      var channels = data.rdef.c.split(","); // c=1|3336:38283$FF0000,2|1649:17015$00FF00
                      if (channels.length != OME.preview_viewport.getChannels().length ||
                        data.rdef.pixel_range != OME.preview_viewport.loadedImg.pixel_range.join(":")) {
                          // images are not compatible
                          $("#rdef-paste-btn")
                            .attr('title', 'Copied settings are not compatible with this image');
                          return;
                        }
                        $("#rdef-paste-btn").prop("disabled", false).removeClass("button-disabled");
                    }
                }
              );

              // disable 'Full Range' button if pixelsType is 'float' or 'double'
              if ($.inArray(OME.preview_viewport.loadedImg.meta.pixelsType, ["float", "double"]) > -1) {
                $("#rdef-fullrange-btn").attr("disabled", "disabled").addClass("button-disabled");
              }

              // viewport.load() is called after pasting rdef or loading. Cache busting rdef thumbnails...
              $("img.rdef").each(function(){
                  var $this = $(this),
                      base_src = $this.attr('src').split('&_=')[0];
                  $this.attr('src', base_src + "&_=random"+Math.random());
              });
            });

            // handle 'Color' checkbox
            $('#rd-wblitz-rmodel').on('click', function(e){
              setModel(OME.preview_viewport, $(this).get(0).checked?'g':'c');
            });

            // handle 'Active' checkbox
            $('#showactive').on('click', function(e){
              $("#preview_tab #rdef-active-area table tr.rdef-window:not(:has(button.pressed))")
                  .css({'display': this.checked? 'none' : ''});
            });

            // Save settings
            $("#rdef-setdef-btn").on('click', function(){
              setImageDefaults(OME.preview_viewport, this, function() {
                OME.refreshThumbnails(
                    {'imageId':{{ manager.image.id }},
                     'ignorePreview': true,
                     'thumbnail_url': "{% url 'get_thumbnails_json' %}",
                     'defaultThumbnail': "{% static 'webgateway/img/image128.png' %}",
                     'thumbnailsBatch': {{ thumbnails_batch|default:50|json_dumps|safe }},
                    }
                );
                updateMyRdef(OME.preview_viewport.getQuery());
              });
            });

            // Reset defaults without saving
            $("#rdef-reset-btn").on('click', function(){
              resetImageDefaults(OME.preview_viewport);
            });

            $("#rdef-minmax-btn").on('click', function(){
              OME.preview_viewport.setChannelMinMax();
              syncRDCW(OME.preview_viewport);
              OME.preview_viewport.save_channels();
              updateUndoRedo(OME.preview_viewport);
            });

            $("#rdef-fullrange-btn").on('click', function(){
              OME.preview_viewport.setChannelFullRange();
              syncRDCW(OME.preview_viewport);
              OME.preview_viewport.save_channels();
              updateUndoRedo(OME.preview_viewport);
            });

            // Undo/redo buttons
            $("#rdef-undo-btn").on('click', function(){
              OME.preview_viewport.undo_channels();
              syncRDCW(OME.preview_viewport);
            });
            $("#rdef-redo-btn").on('click', function(){
              OME.preview_viewport.redo_channels();
              syncRDCW(OME.preview_viewport);
            });

            var rdefs = {{ rdefsJson|safe }};
            // All button events are delegated, so will also apply to new buttons
            $( "#rdef-buttons" )
            .on( "click", "button", function() {
              var $this = $(this),
                rdid = $this.attr('data-rdid'),     // might not know this (if button created by js)
                ownerid = $this.attr('data-ownerid');
              $( "#rdef-buttons button" ).removeClass('clicked');
              $this.addClass('clicked');
              for (var r = 0; r < rdefs.length; r++) {
                if (rdefs[r].id+"" === rdid || rdefs[r].owner.id+"" === ownerid) {
                  OME.preview_viewport.setQuery(rdefs[r]);
                  OME.preview_viewport.doload();
                  syncRDCW(OME.preview_viewport);
                  OME.preview_viewport.save_channels();
                  updateUndoRedo(OME.preview_viewport);
                  break;
                }
              }
            });

            // when user saves, update their rdef button
            var updateMyRdef = function(queryString) {
              var settings = queryString.split("&"),
                defs = {},
                kv;
              for (var s = 0; s < settings.length; s++) {
                kv = settings[s].split("=");
                defs[kv[0]] = kv[1];
              }
              $( "#rdef-buttons button" ).removeClass('clicked');

              var src = "{% url 'render_thumbnail' manager.image.id %}?_=" + Math.random();
              // if we already have a button, update thumb
              var $btn = $("button.rdef[data-ownerid='{{ ome.user.id }}']");
              if ($btn.length > 0) {
                $btn.addClass('clicked');
                // we don't know rdefid but default thumb will be 'ours'
                $('img.rdef', $btn)
                    .attr('src', src)
                    .removeAttr('data-rdid');   // no-longer valid
                // update 'our' rdef
                for (var r = 0; r < rdefs.length; r++) {
                  if (rdefs[r].owner.id+"" === "{{ ome.user.id }}") {
                    rdefs[r].c = defs.c;
                    rdefs[r].model = defs.model;
                    break;
                  }
                }
              } else {
                // No rdef button exists - need to create one and add to rdefs list
                var $lastBtn = $("button.rdef").last(),
                  $newBtn = $lastBtn.clone()
                    .removeAttr('data-rdid')      // don't know new rdef id
                    .attr('data-ownerid','{{ ome.user.id }}')
                    .appendTo($lastBtn.parent());
                  $newBtn.children('img').attr('src', src);
                  $newBtn.children('span').text("{{ ome.user.getFullName }}")
                      .removeClass('owner');
                  $newBtn.addClass('clicked');

                  rdefs.push({
                    'owner': {'id':{{ ome.user.id }}},
                    'c': defs.c,
                    'm': defs.m
                  })
              }
            };


            {% if manager.image.canAnnotate %}

            {% if manager.well %}
            // If we're looking at a well we know parent is plate
              var pid = "plate-{{ manager.well.plate.id.val }}";
            {% else %}
              // For images in Datasets, we get parent from jsTree, using selected image
              // E.g. dataset-123
              var pid = OME.getParentId();
            {% endif %}


            if (pid) {
              $("#rdef-save-all")
                .attr('title', "Apply and Save settings to all images in " + pid)
                .prop('disabled', false).removeClass("button-disabled")
                .on('click', function(){
                  var $span = $('span', this),
                    spanTxt = $span.text();
                  $span.text("Saving...");
                  var typeId = pid.split("-");
                  var rdefQry = OME.preview_viewport.getQuery();
                  // need to paste current settings to all images...
                  var url = "{% url 'webgateway_copy_image_rdef_json' %}"+ "?" + rdefQry;
                  data = {
                      "toids": typeId[1],
                      "to_type": typeId[0],
                      "imageId": OME.preview_viewport.loadedImg.id // Need imageId for 'apply to all'
                  }
                  $.ajax({
                      type: "POST",
                      dataType: 'text',
                      traditional: true,
                      url: url,
                      data: data,
                      success: function(data){
                          $span.text(spanTxt);
                          // update thumbnails
                          OME.refreshThumbnails({
                            'ignorePreview': true,
                            'thumbnail_url': "{% url 'get_thumbnails_json' %}",
                            'defaultThumbnail': "{% static 'webgateway/img/image128.png' %}",
                            'thumbnailsBatch': 1
                          });
                          updateMyRdef(OME.preview_viewport.getQuery());
                      }
                  });
                });
            }
            {% endif %}


            $("#preview_open_viewer").on('click', function(event){
              event.preventDefault();
              var url = $(this).attr('href');
              var vpQuery = OME.preview_viewport.getQuery();
              // remove &zm=50
              vpQuery = vpQuery.replace("&zm=" + OME.preview_viewport.getZoom(), "");
              var hasQuery = url.indexOf('?') > -1;
              window.open(url + (hasQuery ? "&" : "?") + vpQuery, '_blank');
              return false;
            });

            // Find the current "parent" based on the combined jsTree context
            // of selected, opened, and related nodes.  This parent will then
            // be used to provide context when opening image viewers.
            var parent = OME.getParentId();
            if (parent) {
              if (parent.split('-')[0] === 'dataset') {
                var $btn = $("#preview_open_viewer");
                $btn.prop('href', $btn.prop('href') + '?' + parent.replace('-', '='));
              }
            }
        });
    </script>



<!-- VIEWER "Preview"-->
<div class="right_tab_inner">
	
<!-- open-image link -->

    <div>
			<a id="preview_open_viewer"
        href="{% if share and not share.share.isOwned %}{% url 'web_image_viewer' share.share.id manager.image.id %}{% else %}{% url 'web_image_viewer' manager.image.id %}{% endif %}"
        class="btn silver btn_text" alt="View"
        title="Open full viewer" rel="{% content_identifier 'preview' manager.image.id %}"> <!-- rel is used by robot framework, do not remove it! -->
				<span>
                {% trans "Full viewer" %} 
				</span>
			</a>
    </div>

    <div style="clear:both; margin-bottom: 3px"></div>

      <div class="miniview" id="viewport">
      </div>

    <div style="clear:both; height:20px"></div>

    <div style="text-align: left">
      Z: <span id="wblitz-z-curr">?</span>/<span id="wblitz-z-count">?</span> &nbsp
      T: <span id="wblitz-t-curr">1</span>/<span id="wblitz-t-count">1</span>
    </div>

    <ul class="toolbar borderless labels">
      <li>
        <button id="rdef-setdef-btn" class="button button-disabled"
            {% if manager.image.canAnnotate %}
              title="Saves the current settings."
            {% else %}
            title="You don't have permission to save settings."
            {% endif %}
            disabled="disabled">
          <img src="{% static 'webclient/image/icon_save.png' %}" style="position:relative; top:2px" /><br>
            Save
        </button>

        <button id="rdef-save-all" class="button{%if share and not share.share.isOwned or not ome.can_create%} button-disabled{% endif %}"
            title="Cannot apply settings to other images">
          <img src="{% static 'webclient/image/icon_save.png' %}" style="position:relative; top:2px" /><br>
            Save to All
        </button>
      </li>


      <li><button id="rdef-undo-btn" class="button button-disabled"
          title="Undo the last changes to settings" disabled="disabled">
        <img src="{% static "webclient/image/icon_undo16.png" %}" /><br>
        Undo
      </button> </li>
      <li><button id="rdef-redo-btn" class="button button-disabled"
          title="Redo the last changes to settings" disabled="disabled">
        <img src="{% static "webclient/image/icon_redo16.png" %}" /><br>
        Redo
      </button></li>
      
      <li class="seperator"></li>

      <li><button id="rdef-copy-btn" class="button" title="Copy Rendering Settings">
        <img src="{% static "webclient/image/icon_toolbar_copy.png" %}"/><br>
        Copy
      </button></li>
      <li><button id="rdef-paste-btn" class="button button-disabled"
          title="Paste Rendering Settings" disabled="disabled">
        <img src="{% static "webclient/image/icon_toolbar_paste.png" %}"/><br>
        Paste
      </button></li>
    </ul>

    <div id="rdef-container">
      <div id="rdef-postit">
        <div id="rdef-active-area">
          <label title="Enable grayscale rendering mode">
            <input id="rd-wblitz-rmodel" type="checkbox" />
            Grayscale
          </label>
          <label title="Show only active channels">
            <input id="showactive" type="checkbox" />
            Active
          </label>
          <div style="float:right {% if tiledImage %}; color:#bbb{%endif%}"
            {% if tiledImage or share %}
              title="Histogram not supported for tiled images or in share"
            {%else%}
              title="Show histogram of pixel intensities for selected channel"
            {% endif %} >
            <!-- histogram (not supported for Big images) -->
            <input id="showhistogram" type="checkbox" {% if tiledImage or share %}disabled{% endif %}/>
            <label for="showhistogram">Show Histogram</label>
          </div>
          <div id="histogram" style="display:none; width: 100%; height: 125px; background:white; border: solid #ccc 1px; margin-bottom: 6px"></div>
          <table cellspacing="0" style="font-size:0.9em">
            <tr>
            </tr>
          </table>
        </div>
      </div>

      <ul>
        <li>
          <button id="rdef-minmax-btn" title="Each slider will be set to cover the min/max pixel intensities for that channel">
            Min/Max
          </button>
          <button id="rdef-fullrange-btn" title="Each slider will be set to cover the full range of pixel intensities for the image">
            Full Range
          </button>
          <button id="rdef-reset-btn" title="Applies the original imported settings for this image">
            Imported
          </button>
        </li>

        <hr class="thin-margin"/>

        <h3 style="margin-bottom:2px; margin-top:4px">User Settings:</h3>

        <li id='rdef-buttons'>
          {% for rdef in rdefs %}
            <button class='rdef {% if rdef.current %}clicked{% endif %}'
              data-ownerid="{{ rdef.owner.id }}" data-rdid="{{ rdef.id }}">
              <img class='rdef' src="
  {% if share.share.id and not share.share.isOwned %}{% url 'render_thumbnail'  manager.image.id share.share.id%}
  {% else %}{% url 'render_thumbnail' manager.image.id %}{% endif %}?rdefId={{ rdef.id }}"/><br>
              <span {% ifequal manager.image.getDetails.owner.id.val rdef.owner.id %}class="owner"{% endifequal %}>
                {{ rdef.owner.firstName }} {{ rdef.owner.lastName }}
              </span>
            </button>
          {% endfor %}
        </li>
      </ul>
    </div>


</div>
