{% 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">
           <div class="ibox float-e-margins">
               <div class="ibox-content mailbox-content" style="padding-top: 0;padding-left: 1px">
                   <div class="file-manager ">
                       <div id="assetTree" class="ztree">
                       </div>
                       <div class="clearfix"></div>
                   </div>
               </div>
           </div>
       </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 'Active' %}</th>
                       <th class="text-center" >{% trans 'Action' %}</th>
                   </tr>
                  </thead>
                  <tbody>
                  </tbody>
              </table>
          </div>
       </div>
   </div>
</div>
{% 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 onSelected(event, treeNode) {
    setCookie('node_selected', treeNode.id);
    var url = table.ajax.url();
    if (treeNode.meta.type === 'node') {
        url = setUrlParam(url, 'asset', "");
        url = setUrlParam(url, 'node', treeNode.meta.node.id)
    } else {
        url = setUrlParam(url, 'node', "");
        url = setUrlParam(url, 'asset', treeNode.meta.asset.id)
    }
    setCookie('node_selected', treeNode.node_id);
    table.ajax.url(url);
    table.ajax.reload();
}


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


function initTree() {
    var setting = {
        view: {
            dblClickExpand: false,
            showLine: true
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        async: {
			enable: true,
			url: "{% url 'api-assets:node-children-tree' %}?assets=1",
			autoParam:["id=key", "name=n", "level=lv"],
            type: 'get'
		},
        callback: {
            onSelected: onSelected,
            beforeAsync: beforeAsync
        }
    };
    zTree = $.fn.zTree.init($("#assetTree"), setting);
}

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'));
        }
    }

})

</script>
{% endblock %}
