{% extends "webadmin/base.html" %}
{% 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 %}

{% block link %}
    {{ block.super }}
    <link rel="stylesheet" href="{% static "webadmin/css/picklist.css"|add:url_suffix %}" type="text/css" media="screen"/>
    <link rel="stylesheet" href="{% static '3rdparty/jquery.chosen-1.2.0/chosen.css' %}" type="text/css" media="screen"/>
    
    <link rel="stylesheet" href="{% static 'webadmin/css/chosen.css'|add:url_suffix %}" type="text/css" media="screen"/>
    
{% endblock %}

{% block title %}
    {% if eid %}
        {% trans "Edit user" %}
    {% else %}
        {% trans "New User" %}
    {% endif %}

{% endblock %}

{% block script %}
    {{ block.super }}
    <script type="text/javascript" src="{% static "webclient/javascript/jquery.form-3.51.js" %}"></script>
    <script type="text/javascript" src="{% static '3rdparty/jquery.chosen-1.2.0/chosen.jquery.js' %}"></script>
    <script type="text/javascript" src="{% static '3rdparty/jquery.selectboxes-2.2.6.js' %}"></script>
    <style>
        #privileges label {
            width: 160px;
        }
        #privilege_info {
            width: 50%;
            float: left;
            min-height: 100px;
            text-align: right;
            margin: 20px;
            margin-top: 80px;
            font-size: 14px;
        }
        #privilege_info b {
            font-weight: bold;
        }
        #privilege_list {
            width: 40%;
            float: left;
        }
        #id_role input {
            margin-top: -1px;
        }
        #id_role li {
            margin-top: 2px;
        }

    </style>
    <script type="text/javascript">
    $(document).ready(function() 
    {
        var PRIVILEGE_INFO = {
            'Sudo': 'Administrator can log in as another user, with all the permissions of that user',
            'Write': 'Administrator can create data in groups of which he/she is not a member. Also allows annotating, adding attachments to and editing of other users\' data.',
            'Delete': 'Administrator can delete other users\' data',
            'Chgrp': 'Administrator can move others\' data to a different Group',
            'Chown': 'Administrator can transfer others\' data to a different Owner',
            'ModifyGroup': 'Administrator can create and edit groups (but not add or remove users)',
            'ModifyUser': 'Administrator can create and edit other users (but not add them to groups). Recommended to also select <b>Add Users to Groups</b>',
            'ModifyGroupMembership': 'Administrator can add or remove users to groups',
            'Script': 'Administrator can upload "official" OMERO.scripts to the server',
        }
        // Move the user privilege checkboxes into a panel that is only shown when user
        // selects 'restricted_administrator' role.
        // Insert panel after 'id_role' field...
        var $roleDiv = $('#id_role').parent();
        var $privilegePanel = $('#privilege_panel').insertAfter($roleDiv);
        $('.privilege').each(function(){
            $(this).parent().appendTo($('#privileges'));
        });
        var showPrivilegeInfo = function(privilegeId) {
            var privilegeName = privilegeId.replace('id_', '');
            var info = PRIVILEGE_INFO[privilegeName] || " ";
            var labelText = $("label[for='" + privilegeId + "']").text();
            $('#privilege_info').html("<b>" + labelText + "</b> " + info);
        }
        $("#privileges label").on( "mouseover", function() {
            showPrivilegeInfo($(this).prop('for'));
        });
        $("#privileges input").on( "mouseover", function() {
            showPrivilegeInfo(this.id);
        });

        // When User selects "Create and Edit User" privilege, also select "Add Users To Groups"
        $("#id_ModifyUser").on("change", function() {
            var checked = $(this).is(':checked');
            $("#id_ModifyGroupMembership").prop('checked', checked);
        });

        // Since we want to disable removal of 'system' group (id=0) from chosen, this hides the 'X'
        var admin_groups = {{ admin_groups|jsonify|safe }};
        var hideSystemGroupX = function() {
            for (i=0; i<admin_groups.length; i++) {
                var optText = $("#id_other_groups").find("option[value=" + admin_groups[i] + "]").text(),
                    $system_li = $("#id_other_groups_chosen").find("span:contains('"+optText+"')").parent();
                $system_li.find('a').hide();
            }
        }

        // Sync the 'default group' <select> when specified group is added OR removed from selected groups
        var syncDefaultGroupOptions = function(id) {
            var $df = $('#id_default_group'),
                currentDefaultGroup = $df.val();
            var groupSelected = $("#id_other_groups option[value='"+id+"']").prop('selected');

            if (!groupSelected) {
                $("#id_default_group option[value='"+id+"']").remove();
            } else {
                // make sure it's available in 'default_group' <select>
                if ($("#id_default_group option[value='"+id+"']").length == 0) {
                    // ADD it (by cloning corresponding <option> from 'groups' <select>)
                    $df.append($("#id_other_groups option[value='"+id+"']").clone().removeProp('selected'));
                }
            }
            // if only one group
            if( $( "#id_other_groups" ).val() && $( "#id_other_groups" ).val().length === 1) {
                $df.selectOptions($( "#id_other_groups" ).val()[0], true);
            }
            $df.trigger("chosen:updated");
        }

        // Setup chosen plugin on 'Default Group' chooser (only select single group)
        $("#id_default_group").chosen({
            disable_search_threshold:5,
            placeholder_text:'Choose default group'
        });

        // Setup chosen plugin on 'Groups' chooser
        $("#id_other_groups")
            .chosen({placeholder_text:'Type group names to add...'})
            .change(function(evt, data) {
                // In case we've added the system group:
                hideSystemGroupX();

                // If 'system' group added...
                if (data && data.selected === "0") {
                    // If role is disabled...
                    if ($("#id_role_0").prop('disabled')) {
                        // we want to revert change
                        $("#id_other_groups option[value='0']").removeProp('selected');
                        $('#id_other_groups').trigger("chosen:updated");
                    } else {
                        // otherwise 'role' is now 'administrator'
                        $("input[name='role'][value='administrator']").prop('checked', true);
                    }
                }

                // update 'default_group' <select>
                if (data && data.deselected) {
                    syncDefaultGroupOptions(data.deselected);
                } else if (data && data.selected) {
                    syncDefaultGroupOptions(data.selected);
                }
            });

        // Show/hide privileges panel
        var syncPrivilegesPanel = function() {
            // Only show 'privilege panel' when 'restricted_administrator' is picked
            if($("input[name='role'][value='restricted_administrator']").is(':checked')) {
                $("#privilege_panel").slideDown();
            } else {
                $("#privilege_panel").slideUp();
            }
        }

        // When 'role' is changed, might need to add/remove 'system' group from choosers
        $("input[name='role']").click( function(evt) {
            evt.stopPropagation();
            // If role of 'user' is picked, de-select 'system' from the 'default group' chooser
            if($("input[name='role'][value='user']").is(':checked')) {
                $("#id_other_groups option[value='0']").removeProp("selected");
            } else {
                $("#id_other_groups option[value='0']").prop('selected', true);
            }
            $("#id_other_groups").trigger("chosen:updated");
            syncPrivilegesPanel();
            syncDefaultGroupOptions(0);
            // In case we've added the system group:
            hideSystemGroupX();
        });

        // Initial setup:
        syncPrivilegesPanel();
        hideSystemGroupX();
        
        // code for Change Password dialog - NB this is duplicated in myaccount.html. 
        $( "#password_change_dialog" ).dialog({
            autoOpen: false,
            draggable: false,
            resizable: false,
            closeOnEscape: true,
            modal: false,
            dialogClass: 'reddit',
            buttons: {
                "OK": function() {
                    // simply submit the form (AJAX handling set-up above)
                    $("#change_password_form").submit();
                },
                "Cancel": function() {
                    $( this ).dialog( "close" );
                }
            },
            position: { 
                my: 'left center',
                at: 'right center',
                of: $('#change_password'),
                collision: "flip",
                offset: "10 0"
            }
        });
        
        $( "#change_password" ).click(function() {
            // clear fields
            var $pw_form = $("#change_password_form");
            $("div.error", $pw_form).text("");
            $("input[name='password']", $pw_form).val("");
            $("input[name='confirmation']", $pw_form).val("");
            $("input[name='old_password']", $pw_form).val("");
            // show dialog
            $( "#password_change_dialog" ).dialog( "open" );
            return false;
        });
        $("#password_cancel").click(function() {
            $( "#password_change_dialog" ).dialog( "close" );
            return false;
        });
        
        $("#password_change_message").hide();
        $("#change_password_form").ajaxForm({
            beforeSubmit: function(data) {
                // check that both new passwords match, fields aren't empty etc.
                var $pw_form = $("#change_password_form");
                var new_pw = $("input[name='password']", $pw_form).val();
                var conf_pw = $("input[name='confirmation']", $pw_form).val();
                var old_pw = $("input[name='old_password']", $pw_form).val();
                if ($.trim(new_pw).length==0 || $.trim(conf_pw).length==0 || $.trim(old_pw).length==0) {
                    $("div.error", $pw_form).text("All fields must be filled in.");
                    return false;
                }
                if (new_pw != conf_pw) {
                    $("div.error", $pw_form).text("New passwords don't match.");
                    return false;
                }
                if ($.trim(new_pw).length<3 || $.trim(conf_pw).length<3 || $.trim(old_pw).length==0) {
                    $("div.error", $pw_form).text("Passwords should be at least 3 characters long.");
                    return false;
                }
                $( "#password_change_dialog" ).dialog( "close" );
            },
            success: function(html) {
                $("#password_change_message").html(html).show();
            }
        });

    });
    
    </script>

{% endblock %}

{% block center_details %}

{{ block.super }}

<div class="one_column_content">
    {% if eid %}
    <h1>{% trans "Edit User" %}</h1>
    {% else %}
    <h1>{% trans "New User" %}</h1>
    {% endif %}

    <h1><a href="{% url 'waexperimenters' %}" style="position:relative; top:-38px; float:right" title="Go Back to Users">Cancel</a></h1>



    {% if eid %}
    <!-- We are editing existing user -->
    <form action="{% url 'wamanageexperimenterid' "save" eid %}" method="POST" class="standard_form settings_form">{% csrf_token %}

        {% if ldapAuth %}
        <label>LDAP:</label> {{ ldapAuth }}
        {% else %}

        <label>Password</label>
            <a class="btn btn_text silver" id="change_password"
                {% if not can_modify_user or not ome.can_create %} style="pointer-events: none" {% endif %}>
                <span {% if not can_modify_user %} style="color:Gray" {% endif %}>Change User's Password</span>
            </a>
        <span id="password_change_message"></span>
        {% endif %}
        <br />
        <br />
    {% else %}
    <!-- We are creating new user -->
    <form action="{% url 'wamanageexperimenterid' "create" %}" method="POST" class="standard_form settings_form">{% csrf_token %}
    {% endif %}

    <p>{% trans "Fields marked in red are mandatory." %}</p>
        {% for field in form %}
            <div class="exp_field">
            {% if field.errors %}<div style="clear:both">{{ field.errors }}</div>{% endif %}

            {% ifequal field.label_tag form.default_group.label_tag %}
                <!-- default group -->
                <span class="required">{{ field.label_tag }}</span>
                {{ field }}
            {% else %}
                {% ifequal field.label_tag form.other_groups.label_tag %}
                    <!-- other groups -->
                    <span class="required">{{ field.label_tag }}</span>
                    {{ field }}
                {% else %}
                    {% if field.field.required %}
                        <span class="required">{{ field.label_tag }}</span>
                    {% else %}
                        {{ field.label_tag }}
                    {% endif %}
                    {{ field }}
                {% endifequal %}
            {% endifequal %}
            </div>
        {% endfor %}
        
        <br />
        
        <input type="submit" 
            {% if not can_modify_user or not ome.can_create %}
                disabled title="You don't have permissions to edit Users"
            {% endif %}
            value="{% trans 'Save' %}" />
        <div style="clear: both"></div>

    </form>

    {% if eid %}
    <!-- hidden dialog for password change - This is almost duplicated in myaccount.html-->
    <div id="password_change_dialog" title="Change Password">

    <form id="change_password_form" action="{% url 'wamanagechangepasswordid' eid %}" method="POST">{% csrf_token %}

        <table>
            <tbody>
                <tr>
                    <td class="form"><label for="id_old_password">Admin Password</label></td>
                    <td class="input">{{ password_form.old_password }}</td>
                </tr>
                <tr>
                    <td class="form">{{ password_form.password.label_tag }}{% if password_form.password.required %}*{% endif %}</td>
                    <td class="input">{{ password_form.password }}</td>
                </tr>
                <tr>
                    <td class="form">{{ password_form.confirmation.label_tag }}{% if password_form.confirmation.required %}*{% endif %}</td>
                    <td class="input">{{ password_form.confirmation }}</td>
                </tr>

                <tr><td colspan="3">
                    <div class="error"></div>
                </td></tr>
            </tbody>
        </table>
    </form>
    </div>
    {% endif %}

</div>


<div id="privilege_panel" style="display: none">
    <!-- Panel for picking Privileges for 'restricted administrator' -->
    <!-- This is placed in the form and populated by '.privilage' fields by js onload-->
    <div id="privilege_info"></div>
    <div id="privilege_list">
        <h1>Choose user privileges</h1>
        <p>For more info see <a href="https://docs.openmicroscopy.org/latest/omero/sysadmins/restricted-admins.html">administrator privileges</a>.</p>
        <div id="privileges">

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


{% endblock %}


{% block metadata_details %}
    <br/>
{% endblock %}