{% extends "webclient/base/base_container.html" %}
{% load i18n %}


{% 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 %}

{% block link %}
    {{ block.super }}
    <link rel="stylesheet" href="{% static "webgateway/css/ome.jstree_theme.css" %}" type="text/css" />
{% endblock %}

{% block script %}
    {{ block.super }}
    <script type="text/javascript" src="{% static "3rdparty/jquery.jstree-3.3.12/jstree.js" %}"></script>
    <script type="text/javascript" src="{% static "webclient/javascript/jquery.jstree.locate_plugin.js"|add:url_suffix %}"></script>
    <script type="text/javascript" src="{% static "webclient/javascript/jquery.jstree.conditionalselect_plugin.js"|add:url_suffix %}"></script>
    <script type="text/javascript" src="{% static "webclient/javascript/jquery.jstree.ometools_plugin.js"|add:url_suffix %}"></script>
    <script type="text/javascript" src="{% static "webclient/javascript/jquery.jstree.truncatetext_plugin.js"|add:url_suffix %}"></script>

    <script type="text/javascript">

        $(document).ready(function()
        {

            // Disable the groups/users dropdown menu and scripts menu.
            $("#groupsUsersButton")
                .css('background-image', 'url()')
                .attr('title', 'Use "Scope" in form below to search within specific Groups / Users');
            $("#scriptButton")
                .css('opacity', 0.5)
                .attr('title', 'Scripts are disabled for data in shares');
            setTimeout(function(){
                // make sure we remove click handler AFTER it's been added
                $("#groupsUsersButton").off('click');
                $("#scriptButton").off('click');
            },500);
        });

    </script>

    <!-- set-up jsTree, toolbar etc -->
    <script type="text/javascript">

        function enableToolbarButton(name, enabled) {
            if (enabled) {
                $('input#'+name+'Button').removeClass('button-disabled').prop('disabled', false);
            } else {
                $('input#'+name+'Button').addClass('button-disabled').prop('disabled', true);
            }
        };

        function buttonsShowHide(selected, inst) {

            // Disable all unless explicitly enabled below
            var toolbar_config = {
                'removecontent': false
            };

            if (selected.length > 0) {
                // Can only remove images from share that you own
                var node = inst.get_node(selected[0]);
                if (node.type === 'image') {
                    var share = inst.get_node(node.parent);
                    if (share.data.obj.ownerId === {{ ome.user.id }}) {
                        toolbar_config['removecontent'] = true;
                    }
                }
            }

            for (var btnName in toolbar_config) {
                enableToolbarButton(btnName, toolbar_config[btnName]);
            }
        };

        function removeImage(selected, inst) {

            // Disable the nodes
            inst.disable_node(selected);

            // This interface does not support multiple remove, so iterate
            // over deleted images
            $.each(selected, function(index, sel) {
                var node = inst.get_node(sel);

                // Get the parent share id
                var shareId = inst.get_node(inst.get_parent(node)).data.obj.id;
                // Get the image id
                var imageId = node.data.obj.id;

                // AJAX Query to remove the images from the share
                $.ajax({
                    url: '{% url 'manage_action_containers' "removefromshare" "share" %}' + shareId + '/',
                    data : {'source': imageId},
                    dataType: "json",
                    type: "POST",
                    success: function(r){
                        if(eval(r.bad)) {
                            inst.enable_node(node);
                            alert(r.errs);
                        } else {
                            inst.delete_node(node);
                        }
                    },
                    error: function(response) {
                        inst.enable_node(node);
                    }
                });
            });
        };

        $(function() {
            // Select jstree and then cascade handle events and setup the tree.
            var jstree = $("#dataTree")
            .on('changed.jstree', function (e, data) {
                var inst = data.instance;
                buttonsShowHide(inst.get_selected(true), inst);
                OME.tree_selection_changed(data, e);
            })
            .on("click.jstree", ".jstree-anchor", function (e) {
                e.preventDefault();
                var datatree = $.jstree.reference($('#dataTree'));
                // Expand on click (not select because of key navigation)
                if (datatree.is_parent(this)) {
                    datatree.open_node(this);
                }
            })
            .on("dblclick.jstree", ".jstree-anchor", function (e) {
                e.preventDefault();
                var datatree = $.jstree.reference($('#dataTree'));
                var node = datatree.get_node(this);
                if (node) {
                    if (node.type === 'image') {
                        popup_url = "{% url 'webindex' %}";
                        var parent_node = datatree.get_node(datatree.get_parent(node));
                        if (!parent_node.data.obj.isOwned) {
                            popup_url += parent_node.data.obj.id + "/img_detail/" + node.data.obj.id ;
                        } else {
                            popup_url += "img_detail/" + node.data.obj.id ;
                        }
                        //Open the image viewer for this image
                        window.open(popup_url, '_blank');
                    }
                }
            })
            .on('loaded.jstree', function(e, data) {
                // Select root node
                data.instance.select_node('ul > li:first');
            })

            // Setup jstree
            .jstree({
                'plugins': ['types', 'sort', 'locate', 'ometools', 'conditionalselect', 'truncatetext', 'contextmenu'],
                // The jstree core
                'core' : {
                    'themes': {
                        'dots': false,
                        'variant': 'ome'
                    },
                    'data' : {
                        // Configure URL for request
                        'url' : function(node) {
                            // Get the type of the node being expanded
                            // Figure out what type of children it should have
                            // Request the list of children from that url, adding any relevant filters
                            if (node.type === 'experimenter') {
                                return '{% url 'api_shares' %}'
                            } else if (node.type === 'share') {
                                return '{% url 'webindex' %}api/share_images/' + node.data.obj.id + '/';
                            } else if (node.id === '#') {
                                // root node - Always load your own shares
                                return '{% url 'api_experimenter' ome.user.id %}';
                            }
                        },
                        // Gather data for request
                        'data' : function(node) {

                            var payload = {};

                            // Get the data for this query, special case for experimenter as this
                            // data is being passed as 'experimenter_id' below and the tag interface
                            // is expecting either a tagset_id or nothing as the 'id'
                            if (node.hasOwnProperty('data') && node.type != 'experimenter') {
                                if (node.data.hasOwnProperty('obj')) {
                                    // share_id is part of the url itself, see above.
                                    // We only need to handle other containers here:
                                    if (node.type !== 'share') {
                                        payload['id'] = node.data.obj.id;
                                    }
                                }
                            }

                            if (node.hasOwnProperty('data') && node.type === 'experimenter') {
                                payload['member_id'] = node.data.obj.id
                            }

                            if (node.type === 'share') {
                                payload['sizeXYZ'] = true;
                                payload['date'] = true;
                            }

                            return payload;
                        },
                        'cache': false,
                        // Converter is required because the JSON format being returned is not
                        // jstree specific.
                        'converters' : {
                            "text json": function (json) {
                                var data = JSON.parse(json);
                                var jstree_data = [];

                                // Add experimenter to the jstree data structure
                                if (data.hasOwnProperty('experimenter')) {
                                    var value = data.experimenter;
                                    var node = {
                                        'data': {'id': value.id, 'obj': value},
                                        'text': value.firstName + ' ' + value.lastName,
                                        'children': true,
                                        'type': 'experimenter',
                                        'state': {
                                        },
                                        'li_attr': {
                                            // 'class': 'experimenter',
                                            'data-id': value.id
                                        }
                                    };

                                    // Add 'state' opened by default
                                    node.state['opened'] = true;

                                    jstree_data.push(node);

                                }

                                // Add share to the jstree data structure
                                if (data.hasOwnProperty('shares')) {
                                    $.each(data.shares, function(index, value) {
                                        var node = {
                                            'data': {'id': value.id, 'obj': value},
                                            'text': value.id.toString(),
                                            'children': (this.isOwned || (this.active && !this.expired)) && value.childCount > 0 ? true : false,
                                            'type': 'share',
                                            'state' : {
                                                'disabled'  : !this.isOwned && ( !this.active || this.expired )
                                            },
                                            'li_attr': {
                                                'class': this.active ? "" : "inactive",
                                                'data-id': value.id
                                            }
                                        };
                                        jstree_data.push(node);
                                    });
                                }

                                // Add discussion to the jstree data structure
                                if (data.hasOwnProperty('discussions')) {
                                    $.each(data.discussions, function(index, value) {
                                        var node = {
                                            'data': {'id': value.id, 'obj': value},
                                            'text': value.id.toString(),
                                            'children': false,
                                            'type': 'discussion',
                                            'state' : {
                                                'disabled'  : !this.isOwned && ( !this.active || this.expired )
                                            },
                                            'li_attr': {
                                                'class': this.active ? "" : "inactive",
                                                'data-id': value.id
                                            }
                                        };
                                        jstree_data.push(node);
                                    });
                                }

                                // Add images to the jstree data structure
                                if (data.hasOwnProperty('images')) {
                                    $.each(data.images, function(index, value) {
                                        if (value.hasOwnProperty('deleted')){
                                            var node = {
                                                'data': {'id': value.id, 'obj': value},
                                                'text': 'Object deleted',
                                                'children': false,
                                                'type': 'deleted',
                                                'li_attr': {
                                                    'data-id': value.id
                                                }
                                            };
                                        } else {
                                            var node = {
                                                'data': {'id': value.id, 'obj': value},
                                                'text': value.name,
                                                'children': false,
                                                'type': 'image',
                                                'li_attr': {
                                                    'data-id': value.id
                                                }
                                            };
                                        }
                                        jstree_data.push(node);
                                    });
                                }

                                return jstree_data;
                            }

                        }
                    },
                    'check_callback': function(operation, node, node_parent, node_position, more) {
                        var inst = $.jstree.reference(node);
                        // Allow 'delete_node' on images only
                        if (operation === 'delete_node' && inst.get_node(node).type === 'image') {
                            return true;
                        }
                        return false
                    }
                },
                'types' : {
                    '#' : {
                        'valid_children': ['experimenter']
                    },
                    'default': {
                        'draggable': false
                    },
                    'experimenter': {
                        'icon' : '{% static "webclient/image/icon_user.png" %}',
                        'valid_children': ['share', 'discussion']
                    },
                    'share': {
                        'icon' : '{% static "webclient/image/left_sidebar_icon_public.png" %}',
                        'valid_children': ['image']
                    },
                    'discussion': {
                        'icon' : '{% static "webclient/image/wp_protocol16.png" %}'
                    },
                    'image': {
                        'icon': '{% static "webclient/image/image16.png" %}',
                    },
                    'deleted': {
                        'icon': false
                    }

                },
                'sort': function(nodeId1, nodeId2) {
                    var inst = this;
                    var node1 = inst.get_node(nodeId1);
                    var node2 = inst.get_node(nodeId2);
                    if (node2.type == 'image') {
                        return node1.text.toLowerCase() <= node2.text.toLowerCase() ? -1 : 1;
                    }
                    // Nodes are 2 types, "Shares" and "Discussions", but we sort by IDs
                    return parseInt(node2.data.obj.id) <= parseInt(node1.data.obj.id) ? -1 : 1;
                },
                'locate' : {
                    // Returns a key for this node
                    'locate_function': function(node) {
                        // In some cases, this function is called before the data attribute exists
                        // These should be ignored, this will be called again later when it is
                        // populated.
                        if (!node.hasOwnProperty('data') ||
                            node.data === undefined ||
                            node.data === null) {
                            return false;
                        }
                        return node.type + '-' + node.data.obj.id;
                    }
                },
                'conditionalselect' : {
                    // Checks if a selection should be allowed
                    'conditionalselect_function': function(node) {
                        // Disable deleted object nodes
                        if (node.type === 'deleted') {
                            return false;
                        }

                        // Disable multi-type selection of shares AND images
                        var inst = this;
                        var selected = inst.get_selected(true);
                        if (selected.length > 0) {
                            return false;
                        }
                        return true;
                    }
                },
                // disable the browser context menu
                'contextmenu' : {
                    "select_node":true,
                    "items" : function(obj){
                        var config = {};
                        return config;
                    }
                },
            });
        });
    </script>

    <!-- handle toolbar clicks -->
    <script type="text/javascript">
    $(function () {

        $('#removecontentButton').on('click', function() {
            var confirm_remove = OME.confirm_dialog('Remove Image?',
                function() {
                    if(confirm_remove.data("clicked_button") == "OK") {
                        var inst = $.jstree.reference('#dataTree');
                        removeImage(inst.get_selected(), inst);
                        inst.refresh();
                    }
                }
            );
        });

        $('#refreshButton').on('click', function() {
            var inst = $.jstree.reference('#dataTree');
            inst.refresh();
        });

        // We (un)truncate images when the left panel resizes...
        $("#left_panel").on('resize', function(event) {
            var inst = $.jstree.reference('#dataTree');
            inst.redraw(true);
        });

    });
    </script>

    <!-- set up the middle panel to only show the div chosen by <select> -->
    {% include "webclient/data/includes/center_plugin_init.js.html" %}

    <!-- include code to handle primary 'thumbs' middle plugin -->
    {% include "webclient/data/includes/center_plugin.thumbs.js.html" %}


    {% for cp in ome.center_plugins %}
        {% include cp.include %}
    {% endfor %}

{% endblock %}



{% block left %}

<div class="left_panel_content">

<div id="left_panel_tabs" class="left_panel_tabs_container ui-tabs">

    <ul id="left_panel_tab_list" class="ui-tabs-nav">
        <li id="explore_tab" class="ui-state-default"><a href="{% url 'load_template' 'userdata' %}" class="ui-tabs-anchor" title="Explore">{% trans "Explore" %}</a></li>
        <li id="tags_tab" class="ui-state-default"><a href="{% url 'load_template' 'usertags' %}" class="ui-tabs-anchor">{% trans "Tags" %}</a></li>
        <li id="public_tab" class="ui-state-default ui-tabs-active"><a class="ui-tabs-anchor">{% trans "Shares" %}</a></li>
    </ul>

    <div class="left_panel_toolbar" id="Public">
        <div class="toolbar">
            <ul id="buttons">

                <li>
                    <input id="removecontentButton" class="button button-disabled" type="image" src="{% static "webclient/image/icon_toolbar_cut.png" %}" alt="Remove content" title="Remove content" />
                </li>

                <li class=seperator></li>

                <li>
                <input id="refreshButton" class="button" type="image" src="{% static "webclient/image/icon_toolbar_refresh.png" %}" alt="Refresh" title="Refresh">
                </li>

            </ul>
        </div>
    </div>

</div>

<div class="left_panel_tree_container">

    <div style="height: 110px; padding: 15px; box-sizing: border-box;">
        <p>Creating new shares is no longer supported. Previously created shares are shown below.</p>
        <p>Please see <a target="_blank" href="https://www.openmicroscopy.org/omero/features/share/">Sharing your data in
                OMERO</a>
            for alternative workflows.
        </p>
    </div>

    <div id="tree_details" class="left_panel_tree" style="height: calc(100% - 110px)">
        <div class="datashareTree" id="dataTree"></div>
    </div>

</div>

</div>

{% endblock %}


{% block center %}

<div id="content_details"> </div>

{% endblock %}


{% block right %}
<div>
    <div id="annotation_tabs" class="absolute_fill">
        <ul id="annotation_tabs_list">
            <li><a href="#metadata_general">{% trans "General" %}</a></li>
            <!-- include right tabs, as configured in settings.py under "omero.web.ui.right_tabs" -->
            {% for rt in ome.right_plugins %}
                <li><a href="#{{ rt.plugin_id }}">{{ rt.label }}</a></li>
            {% endfor %}
        </ul>
        <div id="metadata_general" class="right_tab_content" ></div>
        <!-- include right tab bodies, as configured in settings.py under "omero.web.ui.right_tabs" -->
        {% for rt in ome.right_plugins %}
            <div id="{{ rt.plugin_id }}" class="right_tab_content"></div>
        {% endfor %}
    </div>
</div>
{% endblock %}
