{% extends 'base.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/select2/select2.min.css' %}" rel="stylesheet">
    <script src="{% static 'js/plugins/select2/select2.full.min.js' %}"></script>
    <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;
        }
        .detail-key {
            width: 70px;
        }
    </style>
{% endblock %}

{% block content %}
<div class="wrapper wrapper-content">
   <div class="row">
       <div class="col-lg-3" id="split-left" style="padding-left: 3px">
           {% include 'assets/_node_tree.html' %}
       </div>
       <div class="col-lg-9 animated fadeInRight" id="split-right">
           <div class="tree-toggle">
               <div class="btn btn-sm btn-primary tree-toggle-btn" onclick="toggle()">
                   <i class="fa fa-angle-left fa-x" id="toggle-icon"></i>
               </div>
           </div>
          <div class="mail-box-header">
              <div class="uc pull-left m-r-5">
                   <a class="btn btn-sm btn-primary btn-create-permission">
                       {% trans "Create permission" %}
                   </a>
              </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>
          </div>
       </div>
   </div>
</div>

<ul class="dropdown-menu search-help">
    <li><a class="search-item" data-value="name">{% trans 'Name' %}</a></li>
    <li><a class="search-item" data-value="is_valid">{% trans 'Validity' %}</a></li>
    <li><a class="search-item" data-value="username">{% trans 'Username' %}</a></li>
    <li><a class="search-item" data-value="user_group">{% trans 'User group' %}</a></li>
    <li><a class="search-item" data-value="ip">IP</a></li>
    <li><a class="search-item" data-value="hostname">{% trans 'Hostname' %}</a></li>
    <li><a class="search-item" data-value="node">{% trans 'Node' %}</a></li>
    <li><a class="search-item" data-value="system_user">{% trans 'System user' %}</a></li>
</ul>
{% 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 makeLabel(data) {
    return "<label class='detail-key'><b>" + data[0] + ": </b></label>" + data[1] + "</br>"
}

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 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', rowData.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" %}?display=1',
        columns: [
            {data: "id"}, {data: "name"}, {data: "users"},
            {data: "user_groups"}, {data: "assets"},
            {data: "nodes"}, {data: "system_users"},
            {data: "is_valid", orderable: false}, {data: "id", orderable: false}
        ],
        select: {},
        op_html: $('#actions').html()
    };
    table = jumpserver.initServerSideDataTable(options);
    return table
}


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

function toggle() {
    if (show === 0) {
        $("#split-left").hide(500, function () {
            $("#split-right").attr("class", "col-lg-12");
            $("#toggle-icon").attr("class", "fa fa-angle-right fa-x");
            show = 1;
        });
    } else {
        $("#split-right").attr("class", "col-lg-9");
        $("#toggle-icon").attr("class", "fa fa-angle-left fa-x");
        $("#split-left").show(500);
        show = 0;
    }
}

$(document).ready(function(){
    initTable();
    initTree();

})
.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', '.btn-create-permission', function () {
    var url = "{% url 'perms:asset-permission-create' %}";
    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', '#permission_list_table_filter input', function (e) {
    e.preventDefault();
    e.stopPropagation();
    var position = $('#permission_list_table_filter input').offset();
    var y = position['top'];
    var x = position['left'];
    x -= 220;
    y += 30;

    $('.search-help').css({"top":y+"px", "left":x+"px", "position": "absolute"});
    $('.dropdown-menu.search-help').show();
}).on('click', '.search-item', function (e) {
    e.preventDefault();
    e.stopPropagation();
    var value = $(this).data('value');
    var old_value = $('#permission_list_table_filter input').val();
    var new_value = old_value + ' ' + value + ':';
    $('#permission_list_table_filter input').val(new_value.trim());
    $('.dropdown-menu.search-help').hide();
    $('#permission_list_table_filter input').focus()
}).on('click', 'body', function (e) {
    $('.dropdown-menu.search-help').hide()
})

</script>
{% endblock %}
