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

{% block custom_head_css_js %}
    <link href="{% static "css/plugins/footable/footable.core.css" %}" rel="stylesheet">
    <link href="{% static 'css/plugins/datepicker/datepicker3.css' %}" rel="stylesheet">
    <link href="{% static 'css/plugins/jstree/style.min.css' %}" rel="stylesheet">
    <link href="{% static 'css/plugins/ztree/awesomeStyle/awesome.css' %}" rel="stylesheet">
    <script type="text/javascript" src="{% static 'js/plugins/ztree/jquery.ztree.all.min.js' %}"></script>
    <style>
        .toggle {
            cursor: pointer;
        }
    </style>
{% endblock %}

{% block table_container %}
     <div class="btn-group uc pull-left m-r-5">
        <button class="btn btn-sm btn-primary btn-create-permission">
            {% trans "Create permission" %}
        </button>
        <button data-toggle="dropdown" class="btn btn-primary btn-sm dropdown-toggle"><span class="caret"></span></button>
        <ul class="dropdown-menu">
            <li><a class="refresh-asset-permission-cache" href="#">{% trans 'Refresh permission cache' %}</a></li>
        </ul>
     </div>
     <table class="table table-striped table-bordered table-hover" id="permission_list_table" style="width: 100%">
         <thead>
         <tr>
              <th></th>
              <th>{% trans 'Name' %}</th>
              <th class="text-center">{% trans 'User' %}</th>
              <th class="text-center">{% trans 'User group' %}</th>
              <th class="text-center">{% trans 'Asset' %}</th>
              <th class="text-center">{% trans 'Node'%}</th>
              <th class="text-center">{% trans 'System user' %}</th>
              <th class="text-center">{% trans 'Validity' %}</th>
              <th class="text-center" >{% trans 'Action' %}</th>
          </tr>
         </thead>
         <tbody>
         </tbody>
     </table>
{% include '_filter_dropdown.html' %}
{% endblock %}

{% block custom_foot_js %}
<script src="{% static "js/plugins/footable/footable.all.min.js" %}"></script>
<script src="{% static 'js/plugins/datepicker/bootstrap-datepicker.js' %}"></script>
<script>
var zTree, table, show = 0;

function onNodeSelected(event, treeNode) {
    setCookie('node_selected', treeNode.id);
    var url = table.ajax.url();
    if (treeNode.meta.type === 'node') {
        url = setUrlParam(url, 'asset_id', "");
        url = setUrlParam(url, 'node_id', treeNode.meta.node.id)
    } else {
        url = setUrlParam(url, 'node_id', "");
        url = setUrlParam(url, 'asset_id', treeNode.meta.asset.id)
    }
    setCookie('node_selected', treeNode.node_id);
    table.ajax.url(url);
    table.ajax.reload();
}


function beforeNodeAsync(treeId, treeNode) {
    if (treeNode) {
        return treeNode.meta.type === 'node'
    }
    return true
}


function format(d) {
    var data = "";
    if (d.users.length > 0 ) {
        data += makeLabel(["{% trans 'User' %}", d.users.join(", ")])
    }
    if (d.user_groups.length > 0) {
        data += makeLabel(["{% trans 'User group' %}", d.user_groups.join(", ")])
    }
    if (d.assets.length > 0) {
       data += makeLabel(["{% trans 'Asset' %}", d.assets.join(", ")])
    }
    if (d.nodes.length > 0) {
        data += makeLabel(["{% trans 'Node' %}", d.nodes.join(", ")])
    }
    if (d.system_users.length > 0) {
        data += makeLabel(["{% trans 'System user' %}", d.system_users.join(", ")])
    }
    if (d.actions.length > 0) {
        data += makeLabel(["{% trans 'Action' %}", d.actions.join(", ")])
    }
    return data
}

function initTable() {
    var options = {
        ele: $('#permission_list_table'),
        toggle: true,
        columnDefs: [
            {targets: 0, createdCell: function (td, cellData, rowData) {
                $(td).addClass("toggle");
                $(td).html("<i class='fa fa-angle-right'></i>");
            }},
            {targets: 1, createdCell: function (td, cellData, rowData) {
                cellData = htmlEscape(cellData);
                var detail_btn = '<a href="{% url "perms:asset-permission-detail" pk=DEFAULT_PK %}">' + cellData + '</a>';
                $(td).html(detail_btn.replace('{{ DEFAULT_PK }}', rowData.id));
            }},
            {targets: 2, createdCell: function (td, cellData) {
                var num = cellData.length;
                $(td).html(num);
            }},
            {targets: 3, createdCell: function (td, cellData) {
                var num = cellData.length;
                $(td).html(num);
            }},
            {targets: 4, createdCell: function (td, cellData) {
                var num = cellData.length;
                $(td).html(num);
            }},
            {targets: 5, createdCell: function (td, cellData) {
                var num = cellData.length;
                $(td).html(num);
            }},
            {targets: 6, createdCell: function (td, cellData) {
                var num = cellData.length;
                $(td).html(num);
            }},
            {targets: 7, createdCell: function (td, cellData) {
                if (!cellData) {
					$(td).html('<i class="fa fa-times text-danger"></i>')
				} else {
					$(td).html('<i class="fa fa-check text-navy"></i>')
				}
            }},
            {targets: 8, createdCell: function (td, cellData, rowData) {
                var name = htmlEscape(rowData.name);
                var update_btn = '<a href="{% url "perms:asset-permission-update" pk=DEFAULT_PK %}" class="btn btn-xs m-l-xs btn-info">{% trans "Update" %}</a>'.replace('{{ DEFAULT_PK }}', cellData);
                var del_btn = '<a class="btn btn-xs btn-danger m-l-xs btn-del" data-uid="{{ DEFAULT_PK }}" mark=1 data-name="99991938">{% trans "Delete" %}</a>'
                    .replace('{{ DEFAULT_PK }}', cellData)
                    .replace('99991938', name);
                if (rowData.inherit) {
                    del_btn = del_btn.replace("mark", "disabled")
                }
				$(td).html(update_btn + del_btn);
            }}
        ],
        ajax_url: '{% url "api-perms:asset-permission-list" %}',
        columns: [
            {data: "id"}, {data: "name"}, {data: "users", orderable: false},
            {data: "user_groups", orderable: false}, {data: "assets", orderable: false},
            {data: "nodes", orderable: false}, {data: "system_users", orderable: false},
            {data: "is_valid", orderable: false}, {data: "id", orderable: false, width: "120px"}
        ],
        select: {},
        op_html: $('#actions').html()
    };
    table = jumpserver.initServerSideDataTable(options);
    return table
}


function initTree() {
    initNodeTree({
        onSelected: onNodeSelected,
        beforeAsync: beforeNodeAsync,
        showMenu: false,
        showAssets: true
    })
}


$(document).ready(function(){
    initTable();
    initTree();
    var filterMenu = [
        {title: "{% trans 'Name' %}", value: "name"},
        {title: "{% trans 'Validity' %}", value: "is_valid"},
        {title: "{% trans 'Username' %}", value: "username"},
        {title: "{% trans 'User group' %}", value: "user_group"},
        {title: "{% trans 'IP' %}", value: "ip"},
        {title: "{% trans 'Hostname' %}", value: "hostname"},
        {title: "{% trans 'Node' %}", value: "node"},
        {title: "{% trans 'System user' %}", value: "system_user"},
        {title: "{% trans 'Inherit' %}", value: "all", submenu: [
            {title: "{% trans 'Include' %}", value: "1"},
            {title: "{% trans 'Exclude' %}", value: "0"},
        ]},
    ];
    initTableFilterDropdown('#permission_list_table_filter input', filterMenu)
})
.on('click', '.btn-del', function () {
    var $this = $(this);
    var uid = $this.data('uid');
    var name = $this.data('name');
    var the_url = '{% url "api-perms:asset-permission-detail" pk=DEFAULT_PK %}'
            .replace('{{ DEFAULT_PK }}', uid);
    objectDelete($this, name, the_url);
})
.on('click', '.refresh-asset-permission-cache', function () {
    var the_url = "{% url 'api-perms:refresh-asset-permission-cache' %}";
    requestApi({
        url: the_url,
        method: 'GET',
        success_message: "{% trans 'Refresh success' %}"
    });
})
.on('click', '.btn-create-permission', function () {
    var url = "{% url 'perms:asset-permission-create' %}";
    if (zTree) {
        var nodes = zTree.getSelectedNodes();
        var _nodes = [];
        var _assets = [];
        $.each(nodes, function (id, node) {
            if (node.meta.type === 'node') {
                _nodes.push(node.meta.node.id)
            } else {
                _assets.push(node.meta.asset.id)
            }
        });
        url += "?assets=" + _assets.join(",") + "&nodes=" + _nodes.join(",");
    }
    window.open(url, '_self');
}).on('click', '.toggle', function (e) {
    e.preventDefault();
    var detailRows = [];
    var tr = $(this).closest('tr');
    var row = table.row(tr);
    var idx = $.inArray(tr.attr('id'), detailRows);

    if (row.child.isShown()) {
        tr.removeClass('details');
        $(this).children('i:first-child').removeClass('fa-angle-down').addClass('fa-angle-right');
        row.child.hide();

        // Remove from the 'open' array
        detailRows.splice(idx, 1);
    }
    else {
        tr.addClass('details');
        $(this).children('i:first-child').removeClass('fa-angle-right').addClass('fa-angle-down');
        row.child(format(row.data())).show();
        // Add to the 'open' array
        if ( idx === -1 ) {
            detailRows.push(tr.attr('id'));
        }
    }
})
.on('click', 'body', function (e) {
    $('.dropdown-menu.search-help').hide()
})

</script>
{% endblock %}
