{% extends '_base_list.html' %}
{% load i18n static %}
{% block table_search %}
    {% include '_csv_import_export.html' %}
{% endblock %}
{% block table_container %}
<div class="uc pull-left m-r-5"><a href="{% url "users:user-create" %}" class="btn btn-sm btn-primary"> {% trans "Create user" %} </a></div>
<table class="table table-striped table-bordered table-hover " id="user_list_table">
    <thead>
        <tr>
            <th class="text-center">
                <input id="" type="checkbox" class="ipt_check_all">
            </th>
            <th class="text-center">{% trans 'Name' %}</th>
            <th class="text-center">{% trans 'Username' %}</th>
            <th class="text-center">{% trans 'Role' %}</th>
            <th class="text-center">{% trans 'User group' %}</th>
            <th class="text-center">{% trans 'Source' %}</th>
            <th class="text-center">{% trans 'Validity' %}</th>
            <th class="text-center">{% trans 'Action' %}</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>
<div id="actions" class="hide">
    <div class="input-group">
        <select class="form-control m-b" style="width: auto" id="slct_bulk_update">
            {% if CURRENT_ORG == 'DEFAULT' %}
                <option value="delete">{% trans 'Delete selected' %}</option>
            {% else %}
                <option value="remove">{% trans 'Remove selected' %}</option>
            {% endif %}
            <option value="update">{% trans 'Update selected' %}</option>
            <option value="deactive">{% trans 'Deactive selected' %}</option>
            <option value="active">{% trans 'Active selected' %}</option>
        </select>
        <div class="input-group-btn pull-left" style="padding-left: 5px;">
            <button id='btn_bulk_update' style="height: 32px;"  class="btn btn-sm btn-primary">
             {% trans 'Submit' %}
            </button>
        </div>
    </div>
</div>
{% endblock %}
{% block content_bottom_left %}{% endblock %}
{% block custom_foot_js %}
<script src="{% static 'js/jquery.form.min.js' %}"></script>
<script>
var usersTable = 0;
function initTable() {
     var options = {
        ele: $('#user_list_table'),
        columnDefs: [
            {targets: 1, createdCell: function (td, cellData, rowData) {
                cellData = htmlEscape(cellData);
                var detail_btn = '<a href="{% url "users:user-detail" pk=DEFAULT_PK %}">' + cellData + '</a>';
                $(td).html(detail_btn.replace("{{ DEFAULT_PK }}", rowData.id));
             }},
            {targets: 3, createdCell: function (td, cellData, rowData) {
                $(td).html(rowData.role_display);
             }},
            {targets: 4, createdCell: function (td, cellData) {
                var innerHtml = cellData.length > 20 ? cellData.substring(0, 20) + '...': cellData;
                $(td).html('<span href="javascript:void(0);" data-toggle="tooltip" title="' + cellData + '">' + innerHtml + '</span>');
             }},
            {targets: 5, createdCell: function (td, cellData, rowData) {
                $(td).html(rowData.source_display);
             }},
            {targets: 6, createdCell: function (td, cellData, rowData) {
                if (cellData) {
                    $(td).html('<i class="fa fa-check text-navy"></i>')
                } else if (!rowData.is_active) {

                    $(td).html('<i class="fa fa-times text-danger inactive"></i>')
                } else if (rowData.is_expired) {
                    $(td).html('<i class="fa fa-times text-danger expired"></i>')
                }
             }},
            {targets: 7, createdCell: function (td, cellData, rowData) {
                var name = htmlEscape(rowData.name);
                var update_btn = "";
                if (rowData.can_update === false){
                    update_btn = '<a class="btn btn-xs disabled btn-info">{% trans "Update" %}</a>';
                }
                else{
                    update_btn = '<a href="{% url "users:user-update" pk=DEFAULT_PK %}" class="btn btn-xs btn-info">{% trans "Update" %}</a>'.replace('00000000-0000-0000-0000-000000000000', cellData);
                }

                var del_btn = "";
                var rm_btn = "";
                if ("{{ CURRENT_ORG }}" === 'DEFAULT'){
                    if (rowData.can_delete === false){
                        del_btn = '<a class="btn btn-xs btn-danger m-l-xs" disabled>{% trans "Delete" %}</a>'
                            .replace('{{ DEFAULT_PK }}', cellData)
                            .replace('99991938', name);
                    } else {
                        del_btn = '<a class="btn btn-xs btn-danger m-l-xs btn_user_delete" data-action="delete" data-uid="{{ DEFAULT_PK }}" data-name="99991938">{% trans "Delete" %}</a>'
                            .replace('{{ DEFAULT_PK }}', cellData)
                            .replace('99991938', name);
                    }
                    $(td).html(update_btn + del_btn)
                }
                else{
                    if (rowData.can_delete === false){
                        rm_btn = '<a class="btn btn-xs btn-warning m-l-xs" disabled>{% trans "Remove" %}</a>'
                            .replace('{{ DEFAULT_PK }}', cellData)
                            .replace('99991938', name);
                    } else {
                        rm_btn = '<a class="btn btn-xs btn-warning m-l-xs btn_user_delete" data-action="remove" data-uid="{{ DEFAULT_PK }}" data-name="99991938">{% trans "Remove" %}</a>'
                            .replace('{{ DEFAULT_PK }}', cellData)
                            .replace('99991938', name);
                    }
                    $(td).html(update_btn + rm_btn)
                }
             }}],
        ajax_url: '{% url "api-users:user-list" %}',
        columns: [
            {data: "id"}, {data: "name" }, {data: "username" },
            {data: "role"},
            {data: "groups_display", orderable: false},
            {data: "source"},
            {data: "is_valid", orderable: false, width: "50px"},
            {data: "id", orderable: false, width: "100px"}
        ],
        op_html: $('#actions').html()
    };
    usersTable = jumpserver.initServerSideDataTable(options);
    return usersTable
}


$(document).ready(function(){
    usersTable = initTable();
    initCsvImportExport(usersTable, "{% trans 'User groups' %}")
}).on('click', '#btn_bulk_update', function(){
    var action = $('#slct_bulk_update').val();
    var id_list = usersTable.selected;
    if (id_list.length === 0) {
        return false;
    }
    var the_url = "{% url 'api-users:user-list' %}";
    var data = {
        'resources': id_list
    };
    function reloadPage() {
        setTimeout( function () {window.location.reload();}, 300);
    }
    function doDeactive() {
        var data = [];
        $.each(id_list, function(index, object_id) {
            var obj = {"pk": object_id, "is_active": false};
            data.push(obj);
        });
        requestApi({
            url: the_url,
            method: 'PATCH',
            body: JSON.stringify(data),
            success: reloadPage
        });
    }
    function doActive() {
        var data = [];
        $.each(id_list, function(index, object_id) {
            var obj = {"pk": object_id, "is_active": true};
            data.push(obj);
        });
        requestApi({
            url: the_url,
            method: 'PATCH',
            body: JSON.stringify(data),
            success: reloadPage
        });
    }
    function doDelete(props) {
        props = props || {};
        swal({
            title: "{% trans 'Are you sure?' %}",
            text: props.text || "{% trans 'This will delete the selected users !!!' %}",
            type: "warning",
            showCancelButton: true,
            cancelButtonText: "{% trans 'Cancel' %}",
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "{% trans 'Confirm' %}",
            closeOnConfirm: false
        },function () {
            function success(data) {
                url = setUrlParam(the_url, 'spm', data.spm);
                function fail() {
                    var msg = "{% trans 'User Deleting failed.' %}";
                    swal("{% trans 'User Delete' %}", msg, "error");
                }
                requestApi({
                    url:url,
                    method:'DELETE',
                    flash_message:true,
                    success:reloadPage,
                    error: props.fail || fail
                 });
            }
            requestApi({
                url: "{% url 'api-common:resources-cache' %}",
                method:'POST',
                body:JSON.stringify(data),
                flash_message:false,
                success:success,
             })
        })
    }

    function doRemove(){
        var props = {
            text: "{% trans 'This will remove the selected users !!' %}",
            fail: function fail(){
                var msg = "{% trans 'User Removing failed.' %}";
                swal("{% trans 'User Remove' %}", msg, "error");
            }
        };
        doDelete(props);
    }

    function doUpdate() {
        function fail(data) {
            toastr.error(JSON.parse(data))
        }
        function success(data) {
            var url = "{% url 'users:user-bulk-update' %}";
            location.href= setUrlParam(url, 'spm', data.spm);
         }
        requestApi({
                url: "{% url 'api-common:resources-cache' %}",
                method:'POST',
                body:JSON.stringify(data),
                flash_message:false,
                success:success,
                error:fail
        })
     }
    switch(action) {
        case 'deactive':
            doDeactive();
            break;
        case 'delete':
            doDelete();
            break;
        case 'remove':
            doRemove();
            break;
        case 'update':
            doUpdate();
            break;
        case 'active':
            doActive();
            break;
        default:
            break;
    }
}).on('click', '.btn_user_delete', function(){
    var $this = $(this);
    var name = $this.data('name');
    var uid = $this.data('uid');
    var action = $this.data('action');
    var title, success_message = null;
    if (action === 'remove'){
        title = "{% trans 'Are you sure about removing it?' %}";
        success_message = "{% trans 'Remove the success' %}";
    }
    var the_url = '{% url "api-users:user-detail" pk=DEFAULT_PK %}'.replace("{{ DEFAULT_PK }}", uid);
    objectDelete($this, name, the_url, null, title, success_message);
}).on('click', '.expired', function () {
    var msg = '{% trans "User is expired" %}';
    toastr.error(msg)
}).on('click', '.inactive', function () {
    var msg = '{% trans 'User is inactive' %}';
    toastr.error(msg)

})
</script>
{% endblock %}

