{% comment %}
<!--
  Copyright (C) 2012 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 %}

    <script type="text/javascript">
        
        $(document).ready(function()
            {
                {% if link_string %}
                $("#link_info_popup_string").val(location.protocol + "//" + location.host + "{{ webclient_path }}?show={{ link_string }}");
                {% endif %}

                // We do this here and in batch_annotate panel
                OME.initToolbarDropdowns();


            {% if image %}
                var parent = OME.getParentId();
                if (parent) {
                    if (parent.split('-')[0] === 'dataset') {
                        var $btn = $("#open_full_viewer");
                        $btn.prop('href', $btn.prop('href') + '?' + parent.replace('-', '='));
                    }
                }
            {% endif %}

                // if batch_annotate panel, we can use obj_labels
                var selectedObjs = [{% for o in obj_labels %}{% if forloop.counter > 1 %},{% endif %}"{{ o.type|lower }}-{{ o.id}}"{% endfor %}];
                var selJson = [{% for o in obj_labels %}{% if forloop.counter > 1 %}, {% endif %}{"id": {{ o.id }}, 'type': '{{ o.type|lower }}', 'name': '{{ o.name }}'  }{% endfor %}];

                // If single object selected
              {% if manager.obj_type %}
                selectedObjs = ["{{ manager.obj_type }}-{{ manager.obj_id }}"];
                selJson = [{'id': '{{ manager.obj_id }}',
                           'name': '{{ manager.obj_name }}',
                           'type': '{{ manager.obj_type }}' }]
              {% endif %}

                var selectedType = selectedObjs.reduce(function(prev, s){
                    return s.split('-')[0] + (selectedObjs.length > 1 ? "s" : "");
                }, "undefined");

              {% if not share %}
                function getOpenwithHtml() {
                  var openwith_html = WEBCLIENT.OPEN_WITH.map(function(v){
                    var label = v.label || v.id;
                    var enabled = false;
                    var tooltip = "Open " + selectedType + " with " + label;

                    if (typeof v.isEnabled === "function") {
                        // If plugin has provided a function 'isEnabled'...
                        // prepare json of selected objects to pass to function
                        enabled = v.isEnabled(selJson, function(enable) {
                          // This callback allows asyn enable/disable of menu item
                          let $a = $(`#right_panel_openwith a[data-openwithid="${v.id}"]`);
                          $a.data('openwith_disabled', !enable);
                          if (!enable) {
                            $a.parent().addClass('disabled');
                          } else {
                            $a.parent().removeClass('disabled');
                          }
                        });
                    }
                    // ...Otherwise if supported_objects list is configured...
                    // v.supported_objects is ['image'] or ['dataset', 'images'] etc.
                    else if (typeof v.supported_objects === "object" && v.supported_objects.length > 0) {
                        enabled = v.supported_objects.reduce(function(prev, supported){
                            // e.g. If supported_objects is 'images'...
                            return prev || supported.indexOf(selectedType) > -1;  // ... selType 'image' OR 'images' are > -1
                        }, false);
                    };
                    var dtypes = selectedObjs.map(function(o){
                      return o.replace('-', '=');
                    });
                    var query = dtypes.join("&");
                    // default url includes objects in query
                    var url = v.url + "?" + query;
                    // if plugin has added a url provider,
                    // use it to update the url...
                    if (v.getUrl) {
                        url = v.getUrl(selJson, v.url);
                        if (typeof url === 'function') {
                          // handle click below
                          url = '#';
                        }
                    }
                    var liClass = "";
                    if (!enabled) {
                        liClass = "disabled";
                        tooltip = tooltip.replace("Open", "Cannot open");
                    }
                    var html = `
                      <li class='${ liClass }'>
                        <a title='${ tooltip }'
                          target='_blank'
                          href = '${ url }'
                          data-openwith_disabled=${ !enabled }
                          data-openwithid='${ v.id }' >
                          ${ label }
                        </a>
                      </li>
                    `
                    return html;
                  
                  });
                  return openwith_html.join("");
                }

                // Only build html when we need it
                $("#show_openwith_menu").on('click', function() {
                  let html = getOpenwithHtml();
                  $("#right_panel_openwith").html(html);
                });

                // Listen for clicks on Open-with menu items in case we want to handle with a function
                // instead of default link behaviour
                $("#right_panel_openwith").on("click", "a", function (event) {
                  var $a = $(this);
                  if ($a.data('openwith_disabled')) {
                    event.preventDefault();
                    return;
                  }
                  if ($a.attr('href') === '#') {
                    event.preventDefault();
                    let openwith_id = $a.data('openwithid');
                    let ow = WEBCLIENT.OPEN_WITH.filter(o => o.id === openwith_id)[0];
                    if (ow) {
                      let fn = ow.getUrl(selJson, ow.url);
                      if (typeof fn === 'function') {
                        fn();
                      }
                    }
                  }
                });

              {% endif %}
            
        });
    </script>


<div style="position:relative">

    {% if not share %}
    <!-- open-image link -->
    <button id="show_link_btn" class="btn silver btn_link" title="Link to this {{ manager.obj_type }}">
        <span></span>
    </button>
    <div id="link_info_popup" class="info_popup" style="right:0px; top:30px; padding:4px; display:none">

        <table>
          <tr><td>
            <!-- In 'batch_annotate' panel we have 'link_string'. In 'metadata_general' we use js to get value -->
            <input type="text" size="30" id="link_info_popup_string" />
          </td><td>
            <img title="Close" src="{% static 'webgateway/img/close.gif' %}" />
          </td></tr>
        </table>
    </div>
    {% endif %}

    <!-- This is used for 'batch annotate' panel with 'filesetCount'... -->
    <!-- ... and for single images -->

    {% if image or filesetInfo %}
    <!-- download options -->
    <div class="toolbar_dropdown">
        <button class="btn silver btn_download" title="Download Image as...">
            <span></span>
        </button>
        <ul class="dropdown">
        {% if canDownload %}
            <!-- Here we handle a single image (in metadata general) - see below for multiple images (batch annotate) -->
            {% if not share and image.getImportedFilesInfo.count %}
              {% with filesetInfo=image.getImportedFilesInfo %}
            <li>
                <!-- if we have a single orig file, download directly. Otherwise popup a 
                  'preparing zip' download placeholder -->
                <a id="download-origfile" 
                  {% if filesetInfo.count == 1 %}
                    href="{% url 'archived_files' image.id %}"
                  {% else %}
                    href="#"
                    onClick="return OME.openPopup('{% url 'download_placeholder' %}?ids=image-{{ image.id }}&fileCount={{ fileCount }}&name={{ image.name }}');"
                  {% endif %}
                title="Download {{ filesetInfo.count }} original imported file{{ filesetInfo.count|pluralize:'s'}} ({{ filesetInfo.size|filesizeformat }})"
                >
                Download...</a>
            </li>
              {% endwith %}
            <li>
              <a href="{% url 'download_orig_metadata' image.id %}"
                  title="Download Original Metadata as a text file">
                Download Original Metadata
              </a>
            </li>
            <!-- Here we handle multiple images (batch annotate panel) -->
            {% elif filesetInfo %}
            <li {% if not filesetInfo.count %}class='disabled'{% endif %}>
              <a id="download-origfile"
                {% if filesetInfo.count == 0 %}
                  href="#"
                {% else %}
                  {% if filesetInfo.count == 1 %}
                    href="{% url 'archived_files' %}?{{ obj_string }}"
                  {% else %}
                    href="#"
                    onClick="return OME.openPopup('{% url 'download_placeholder' %}?ids={{ link_string }}&fileCount={{ filesetInfo.count }}&index={{ index }}');"
                  {% endif %}
                {% endif %}
                title="Download {{ filesetInfo.count }} original imported file{{ filesetInfo.count|pluralize:'s'}} ({{ filesetInfo.size|filesizeformat }})"
                >
                Download...</a>
            </li>
            <li class="disabled">
              <a href="#"
                  title="Download Original Metadata (for single images only)">
                Download Original Metadata
              </a>
            </li>
            {% else %}
            <li class="disabled">
              <a title="No original imported files to download">Download...</a>
            </li>
            {% endif %}
        <!-- endif canDownload -->
        {% endif %}

        {% if not share %}
            {% if image and not image.requiresPixelsPyramid and ome.can_create %}
            <li>
                <a id="create-ometiff" href="{% url 'ome_tiff_script' image.id %}" 
                title="Create OME-TIFF File for Download">Export as OME-TIFF...</a>
            </li>
            {% else %}
            <li class="disabled">
                <a href="#" class="disabled"
                title="Create OME-TIFF File for Download">Export as OME-TIFF...</a>
            </li>
            {% endif %}
        {% endif %}
            
            {% if image %}
              {% with ex=canExportAsJpg %}
              <li {% if not ex %}class="disabled"{% endif %}>
                <a 
                  {% if not ex %}
                      href="#" class="disabled" title="Image is too big to download as JPEG"
                  {% else %}
                      {% if share and not share.share.isOwned %}
                          href="{% url 'web_render_image_download' share_id=share.share.id iid=image.id %}"
                      {% else %}
                          href="{% url 'web_render_image_download' image.id %}"
                      {% endif %}
                      title="Download as JPEG"
                  {% endif %}
                  >
                  Export as JPEG
                </a>
              </li>
              <li {% if not ex %}class="disabled"{% endif %}>
                <a 
                  {% if not ex %}
                      href="#" class="disabled" title="Image is too big to download as PNG"
                  {% else %}
                      {% if share and not share.share.isOwned %}
                          href="{% url 'web_render_image_download' share_id=share.share.id iid=image.id %}?format=png"
                      {% else %}
                          href="{% url 'web_render_image_download' image.id %}?format=png"
                      {% endif %}
                      title="Download as PNG"
                  {% endif %}
                  >
                  Export as PNG
                </a>
              </li>
              <li {% if not ex %}class="disabled"{% endif %}>
                <a
                  {% if not ex %}
                      href="#" class="disabled" title="Image is too big to download as TIFF"
                  {% else %}
                      {% if share and not share.share.isOwned %}
                          href="{% url 'web_render_image_download' share_id=share.share.id iid=image.id %}?format=tif"
                      {% else %}
                          href="{% url 'web_render_image_download' image.id %}?format=tif"
                      {% endif %}
                      title="Download as TIFF"
                  {% endif %}
                  >
                  Export as TIFF
                </a>
              </li>
              {% endwith %}
            {% else %}
              {% if filesetInfo %}
              {% with ex=canExportAsJpg %}
              <li {% if not ex %}class="disabled"{% endif %}>
                <a href="#"
                  {% if not ex %}
                      class="disabled" title="Images are too big to download as JPEGs"
                  {% else %}
                      onClick="return OME.openPopup('{% url 'download_placeholder' %}?ids={{ link_string }}&format=jpeg&index={{ index }}');"
                      title="Download as JPEGs (zip)"
                  {% endif %}
                  >
                  Export as JPEG
                </a>
              </li>
              <li {% if not ex %}class="disabled"{% endif %}>
                <a href="#"
                  {% if not ex %}
                      class="disabled" title="Images are too big to download as PNGs"
                  {% else %}
                      onClick="return OME.openPopup('{% url 'download_placeholder' %}?ids={{ link_string }}&format=png&index={{ index }}');"
                      title="Download as PNGs (zip)"
                  {% endif %}
                  >
                  Export as PNG
                </a>
              </li>
              <li {% if not ex %}class="disabled"{% endif %}>
                <a href="#"
                  {% if not ex %}
                      class="disabled" title="Images are too big to download as TIFFs"
                  {% else %}
                      onClick="return OME.openPopup('{% url 'download_placeholder' %}?ids={{ link_string }}&format=tif&index={{ index }}');"
                      title="Download as TIFFs (zip)"
                  {% endif %}
                  >
                  Export as TIFF
                </a>
              </li>
              {% endwith %}
              {% endif %}
            {% endif %}
        </ul>
    </div>

    {% if not share %}
    {% if image.showOriginalFilePaths %}
      <!-- show original file paths -->
      <button id="show_fs_files_btn" class="btn silver btn_fspath" title="Show Fileset ID and file paths on server">
        <span></span>
      </button>
    {% endif %}

      {% if image %}
      <button id="show_image_hierarchy" class="btn silver btn_hierarchy" title="Show parent Projects & Datasets">
        <span></span>
      </button>
      {% endif %}
    {% endif %}
    {% endif %}


    <!-- Publishing Options (Figure Scripts) -->
    {% if not share %}
    {% if not differentGroups and ome.can_create %}
    {% include "webclient/annotations/includes/figure_scripts_menu.html" %}
    {% endif %}
    {% endif %}
    


    <div style="position: absolute; left: 0">
      {% if image %}
      <a class="btn silver btn_text" style="height: 18px"
              id="open_full_viewer" target="_blank"
              {% if share and not share.share.isOwned %}
                  href="{% url 'web_image_viewer' share.share.id image.id %}"
              {% else %}
                  href="{% url 'web_image_viewer' image.id %}"
              {% endif %}
              title="Open full image viewer in new tab">
          <span>
              Full viewer
          </span>
      </a>
      {% endif %}


      <div class="toolbar_dropdown">
          {% if not share %}
          <button id="show_openwith_menu" class="btn silver btn_openwith" title="Open with..." style="height: 20px">
              <span></span>
          </button>
          <ul id="right_panel_openwith" class="dropdown dropdown_right">
          </ul>
          {% endif %}
      </div>
  </div>

</div>
<div style="clear:both"></div>


<!-- panel for extra info shown by toolbar buttons if needed -->
<div id="toolbar_info_panel" style="display:none; background: #fff; border: solid 1px #ddd; margin:5px 0">
    <img title="Close" src="{% static 'webgateway/img/close.gif' %}" style="float:right; margin:3px"/>
    <div class="panel_title" style="margin: 4px">
        <!-- text loaded here -->
    </div>
    <div class="panel_div"></div>
    <div style="clear:both"></div>
</div>

<div id="link_info_popup" class="info_popup" style="right:0px; top:30px; padding:4px; display:none">
    <input type="text" size="30">
    <img title="Close" src="{% static 'webgateway/img/close.gif' %}" />
</div>
