{% extends 'base.html' %}
{% load static %}
{% load i18n %}

{% block custom_head_css_js %}
    <link href="{% static 'css/plugins/select2/select2.min.css' %}" rel="stylesheet">
    <link href="{% static "css/plugins/sweetalert/sweetalert.css" %}" rel="stylesheet">
    <script src="{% static 'js/plugins/select2/select2.full.min.js' %}"></script>
    <script src="{% static "js/plugins/sweetalert/sweetalert.min.js" %}"></script>
{% endblock %}
{% block content %}
    <div class="wrapper wrapper-content animated fadeInRight">
        <div class="row">
            <div class="col-sm-12">
                <div class="ibox float-e-margins">
                    <div class="panel-options">
                        <ul class="nav nav-tabs">
                            <li class="active">
                                <a href="{% url 'users:user-detail' pk=user_object.id %}" class="text-center"><i class="fa fa-laptop"></i> {% trans 'User detail' %} </a>
                            </li>
                            <li>
                                <a href="{% url 'users:user-granted-asset' pk=user_object.id %}" class="text-center"><i class="fa fa-cubes"></i> {% trans 'Asset granted' %}</a>
                            </li>
                            <li class="pull-right">
                                <a class="btn btn-outline btn-default" href="{% url 'users:user-update' pk=user_object.id %}"><i class="fa fa-edit"></i>{% trans 'Update' %}</a>
                            </li>

                            <li class="pull-right">
                                <a class="btn btn-outline {% if request.user != user_object and user_object.username != "admin" %} btn-danger btn-delete-user {% else %} disabled {% endif %}">
                                    <i class="fa fa-trash-o"></i>{% trans 'Delete' %}
                                </a>
                            </li>
                        </ul>
                    </div>
                    <div class="tab-content">
                        <div class="col-sm-8" style="padding-left: 0">
                            <div class="ibox float-e-margins">
                                <div class="ibox-title">
                                    <span class="label"><b>{{ user_object.name }}</b></span>
                                    <div class="ibox-tools">
                                        <a class="collapse-link">
                                            <i class="fa fa-chevron-up"></i>
                                        </a>
                                        <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                                            <i class="fa fa-wrench"></i>
                                        </a>
                                        <ul class="dropdown-menu dropdown-user">
                                        </ul>
                                        <a class="close-link">
                                            <i class="fa fa-times"></i>
                                        </a>
                                    </div>
                                </div>
                                <div class="ibox-content">
                                    <table class="table">
                                        <tbody>
                                        <tr class="no-borders-tr">
                                            <td colspan="2">
                                                <img src="{{ user_object.avatar_url }}" class="img-circle" width="64" height="64">
                                            </td>
                                        </tr>
                                        <tr>
                                            <td width="20%">{% trans 'Name' %}:</td>
                                            <td><b>{{ user_object.name }}</b></td>
                                        </tr>
                                        <tr>
                                            <td>{% trans 'Username' %}:</td>
                                            <td><b>{{ user_object.username }}</b></td>
                                        </tr>
                                        <tr>
                                            <td>{% trans 'Email' %}:</td>
                                            <td><b>{{ user_object.email }}</b></td>
                                        </tr>
                                        {% if user.phone %}
                                            <tr>
                                                <td>{% trans 'Phone' %}:</td>
                                                <td><b>{{ user_object.phone }}</b></td>
                                            </tr>
                                        {% endif %}
                                        {% if user_object.wechat %}
                                            <tr>
                                                <td>{% trans 'Wechat' %}:</td>
                                                <td><b>{{ user_object.wechat }}</b></td>
                                            </tr>
                                        {% endif %}
                                        <tr>
                                            <td>{% trans 'Role' %}:</td>
                                            <td><b>{{ user_object.get_role_display }}</b></td>
                                        </tr>
{#                                        <tr>#}
{#                                            <td>{% trans 'Enable OTP' %}:</td>#}
{#                                            <td><b>{{ user_object.enable_otp|yesno:"Yes,No,Unknown"}}</b></td>#}
{#                                        </tr>#}
                                        <tr>
                                            <td>{% trans 'Date expired' %}:</td>
                                            <td><b>{{ user_object.date_expired|date:"Y-m-j H:i:s" }}</b></td>
                                        </tr>
                                        <tr>
                                            <td>{% trans 'Created by' %}:</td>
                                            <td><b>{{ user_object.created_by }}</b></td>
                                        </tr>
                                        <tr>
                                            <td>{% trans 'Date joined' %}:</td>
                                            <td><b>{{ user_object.date_joined|date:"Y-m-j H:i:s" }}</b></td>
                                        </tr>
                                        <tr>
                                            <td>{% trans 'Last login' %}:</td>
                                            <td><b>{{ user_object.last_login|date:"Y-m-j H:i:s" }}</b></td>
                                        </tr>
                                        <tr>
                                            <td>{% trans 'Comment' %}:</td>
                                            <td><b>{{ user_object.comment }}</b></td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-4" style="padding-left: 0;padding-right: 0">
                            <div class="panel panel-primary">
                                <div class="panel-heading">
                                    <i class="fa fa-info-circle"></i> {% trans 'Quick modify' %}
                                </div>
                                <div class="panel-body">
                                    <table class="table">
                                        <tbody>
                                        <tr class="no-borders-tr">
                                          <td width="50%">{% trans 'Active' %}:</td>
                                            <td><span class="pull-right">
                                                <div class="switch">
                                                    <div class="onoffswitch">
                                                        <input type="checkbox" {% if user_object.is_active %} checked {% endif %} {% if request.user == user_object %} disabled {% endif %} class="onoffswitch-checkbox" id="is_active">
                                                        <label class="onoffswitch-label" for="is_active">
                                                            <span class="onoffswitch-inner"></span>
                                                            <span class="onoffswitch-switch"></span>
                                                        </label>
                                                    </div>
                                                </div>
                                            </span></td>
                                        </tr>
{#                                        <tr>#}
{#                                          <td>{% trans 'Enable OTP' %}:</td>#}
{#                                            <td><span class="pull-right">#}
{#                                                <div class="switch">#}
{#                                                    <div class="onoffswitch">#}
{#                                                        <input type="checkbox" class="onoffswitch-checkbox" {% if user_object.enable_otp %} checked {% endif %}#}
{#                                                               id="enable_otp">#}
{#                                                        <label class="onoffswitch-label" for="enable_otp">#}
{#                                                            <span class="onoffswitch-inner"></span>#}
{#                                                            <span class="onoffswitch-switch"></span>#}
{#                                                        </label>#}
{#                                                    </div>#}
{#                                                </div>#}
{#                                            </span></td>#}
{#                                        </tr>#}
                                        <tr>
                                            <td>{% trans 'Send reset password mail' %}:</td>
                                            <td>
                                                <span class="pull-right">
                                                    <button type="button" class="btn btn-primary btn-xs" {% if request.user == user_object %} disabled="disabled" {% endif %} id="btn-reset-password" style="width: 54px">{% trans 'Send' %}</button>
                                                </span>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>{% trans 'Send reset ssh key mail' %}:</td>
                                            <td>
                                                <span class="pull-right">
                                                    <button type="button" class="btn btn-primary btn-xs" {% if request.user == user_object %} disabled="disabled" {% endif %} id="btn-reset-pk" style="width: 54px;">{% trans 'Send' %}</button>
                                                </span>
                                            </td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <div class="panel panel-info">
                                <div class="panel-heading">
                                    <i class="fa fa-info-circle"></i> {% trans 'User group' %}
                                </div>
                                <div class="panel-body">
                                    <table class="table group_edit">
                                        <tbody>
                                        <form>
                                            <tr>
                                                <td colspan="2" class="no-borders">
                                                    <select data-placeholder="{% trans 'Join user groups' %}" id="groups_selected" class="select2" style="width: 100%" multiple="" tabindex="4">
                                                        {% for group in groups %}
                                                        <option value="{{ group.id }}" id="opt_{{ group.id }}" >{{ group.name }}</option>
                                                        {% endfor %}
                                                    </select>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan="2" class="no-borders">
                                                    <button type="button" class="btn btn-info btn-small" id="btn_join_group">{% trans 'Join' %}</button>
                                                </td>
                                            </tr>
                                        </form>

                                        {% for group in user_object.groups.all %}
                                        <tr>
                                          <td >
                                              <b class="bdg_group" data-gid={{ group.id }}>{{ group.name }}</b>
                                          </td>
                                          <td>
                                              <button class="btn btn-danger pull-right btn-xs btn_leave_group" type="button"><i class="fa fa-minus"></i></button>
                                          </td>
                                        </tr>
                                        {% endfor %}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% include 'users/_user_update_pk_modal.html' %}
{% endblock %}
{% block custom_foot_js %}
<script>
jumpserver.nodes_selected = {};

function updateUserGroups(groups) {
    var the_url = "{% url 'api-users:user-update-group' pk=user_object.id %}";
    var body = {
        groups: Object.assign([], groups)
    };
    var success = function(data) {
        // remove all the selected groups from select > option and rendered ul element;
        $('.select2-selection__rendered').empty();
        $('#groups_selected').val('');
        $.map(jumpserver.nodes_selected, function(group_name, index) {
            $('#opt_' + index).remove();
            // change tr html of user groups.
            $('.group_edit tbody').append(
                '<tr>' +
                '<td><b class="bdg_group" data-gid="' + index + '">' + group_name + '</b></td>' +
                '<td><button class="btn btn-danger btn-xs pull-right btn_leave_group" type="button"><i class="fa fa-minus"></i></button></td>' +
                '</tr>'
            )
        });
        // clear jumpserver.groups_selected
        jumpserver.nodes_selected = {};
    };
    APIUpdateAttr({
        url: the_url,
        body: JSON.stringify(body),
        success: success
    });
}

$(document).ready(function() {
    $('.select2').select2()
        .on('select2:select', function(evt) {
            var data = evt.params.data;
            jumpserver.nodes_selected[data.id] = data.text;
        })
        .on('select2:unselect', function(evt) {
            var data = evt.params.data;
            delete jumpserver.nodes_selected[data.id];
        })
})
.on('click', '#is_active', function() {
    var the_url = "{% url 'api-users:user-detail' pk=user_object.id %}";
    var checked = $(this).prop('checked');
    var body = {
        'is_active': checked
    };
    var success = '{% trans "Update successfully!" %}';
    APIUpdateAttr({
        url: the_url,
        body: JSON.stringify(body),
        success_message: success
    });
})
{#.on('click', '#enable_otp', function() {#}
{#    var the_url = "{% url 'api-users:user-detail' pk=user_object.id %}";#}
{#    var checked = $(this).prop('checked');#}
{#    var body = {#}
{#        'enable_otp': checked#}
{#    };#}
{#    var success = '{% trans "Update successfully!" %}';#}
{#    APIUpdateAttr({#}
{#        url: the_url,#}
{#        body: JSON.stringify(body),#}
{#        success_message: success#}
{#    });#}
{# });#}
.on('click', '#btn_join_group', function() {
    if (Object.keys(jumpserver.nodes_selected).length === 0) {
        return false;
    }
    var groups = $('.bdg_group').map(function() {
        return $(this).data('gid');
    }).get();
    $.map(jumpserver.nodes_selected, function(value, index) {
        groups.push(index);
        $('#opt_' + index).remove();
    });
    updateUserGroups(groups)
}).on('click', '.btn_leave_group', function() {
    var $this = $(this);
    var $tr = $this.closest('tr');
    var $badge = $tr.find('.bdg_group');
    var gid = $badge.data('gid');
    var group_name = $badge.html() || $badge.text();
    $('#groups_selected').append(
        '<option value="' + gid + '" id="opt_' + gid + '">' + group_name + '</option>'
    );
    $tr.remove();
    var groups = $('.bdg_group').map(function() {
        return $(this).data('gid');
    }).get();
    updateUserGroups(groups)
}).on('click', '#btn-reset-password', function() {
    function doReset() {
        var the_url = '{% url "api-users:user-reset-password" pk=user_object.id %}';
        var body = {};
        var success = function() {
            var msg = "{% trans "An e-mail has been sent to the user`s mailbox." %}";
            swal("{% trans 'Reset password' %}", msg, "success");
        };
        APIUpdateAttr({
            url: the_url,
            body: JSON.stringify(body),
            success: success
        });
    }
    swal({
        title: "{% trans 'Are you sure?' %}",
        text: "{% trans "This will reset the user password and send a reset mail"%}",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "{% trans 'Confirm' %}",
        closeOnConfirm: false
    }, function() {
        doReset();
    });
}).on('click', '#btn-reset-pk', function() {
    function doReset() {
        var the_url = '{% url "api-users:user-public-key-reset" pk=user_object.id %}';
        var body = {};
        var success = function() {
            var msg = "{% trans 'The reset-ssh-public-key E-mail has been sent successfully. Please inform the user to update his new ssh public key.' %}";
            swal("{% trans 'Reset SSH public key' %}", msg, "success");
        };
        APIUpdateAttr({
            url: the_url,
            body: body,
            success: success
        });
    }
    swal({
        title: "{% trans 'Are you sure?' %}",
        text: "{% trans 'This will reset the user public key and send a reset mail' %}",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "{% trans 'Confirm' %}",
        closeOnConfirm: false
    }, function() {
        doReset();
    });
}).on('click', '#btn-user-update-pk', function(){
    var $this = $(this);
    var pk = $('#txt_pk').val();
    var the_url = '{% url "api-users:user-public-key-reset" pk=user.id %}';
    var body = {'_public_key': pk};
    var success = function() {
        $('#txt_pk').val('');
        $this.closest('.modal').modal('hide');
        var msg = "{% trans 'Successfully updated the SSH public key.' %}";
        swal("{% trans 'User SSH public key update' %}", msg, "success");
    };
    var fail = function(msg) {
        swal({
            title: "{% trans 'User SSH public key update' %}",
            text: msg,
            type: "error",
            showCancelButton: false,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "{% trans 'Confirm' %}",
            closeOnConfirm: true
            }, function () {
              $('#txt_pk').focus();
            }
        );
    };
    APIUpdateAttr({ url: the_url, body: JSON.stringify(body), success: success, error: fail});
}).on('click', '.btn-delete-user', function () {
    var $this = $(this);
    var name = "{{ user.name }}";
    var uid = "{{ user.id }}";
    var the_url = '{% url "api-users:user-detail" pk=DEFAULT_PK %}'.replace('{{ DEFAULT_PK }}', uid);
    var redirect_url = "{% url 'users:user-list' %}";
    objectDelete($this, name, the_url, redirect_url);
})
</script>
{% endblock %}
