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

{% block custom_head_css_js %}
    <link href="{% static 'css/plugins/select2/select2.min.css' %}" rel="stylesheet">
    <script src="{% static 'js/plugins/select2/select2.full.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>
                                <a href="{% url 'assets:system-user-detail' pk=system_user.id %}" class="text-center"><i class="fa fa-laptop"></i> {% trans 'Detail' %} </a>
                            </li>
                            <li class="active">
                                <a href="{% url 'assets:system-user-asset' pk=system_user.id %}" class="text-center">
                                <i class="fa fa-bar-chart-o"></i> {% trans 'Assets' %}
                                </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 style="float: left">{% trans 'Assets of ' %} <b>{{ system_user.name }} </b><span class="badge">{{ paginator.count }}</span></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 table-hover" id="system_user_list">
                                        <thead>
                                            <tr>
                                                <th>{% trans 'Hostname' %}</th>
                                                <th>{% trans 'IP' %}</th>
                                                <th>{% trans 'Port' %}</th>
                                                <th>{% trans 'Reachable' %}</th>
                                                <th>{% trans 'Action' %}</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                        </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 update' %}
                                </div>
                                <div class="panel-body">
                                    <table class="table">
                                        <tbody>
                                        <tr class="no-borders-tr">
                                            <td width="50%">{% trans 'Test assets connective' %}:</td>
                                            <td>
                                                <span style="float: right">
                                                    <button type="button" class="btn btn-primary btn-xs btn-test-connective" style="width: 54px">{% trans 'Test' %}</button>
                                                </span>
                                            </td>
                                        </tr>
                                        {% if system_user.auto_push %}
                                        <tr>
                                            <td width="50%">{% trans 'Push system user now' %}:</td>
                                            <td>
                                                <span style="float: right">
                                                    <button type="button" class="btn btn-primary btn-xs btn-push" style="width: 54px">{% trans 'Push' %}</button>
                                                </span>
                                            </td>
                                        </tr>
                                        {% endif %}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="panel panel-info">
                                <div class="panel-heading">
                                    <i class="fa fa-info-circle"></i> {% trans 'Nodes' %}
                                </div>
                                <div class="panel-body">
                                    <table class="table node_edit" id="add-asset2group">
                                        <tbody>
                                        <form>
                                            <tr>
                                                <td colspan="2" class="no-borders">
                                                    <select data-placeholder="{% trans 'Add to node' %}" id="node_selected" class="select2" style="width: 100%" multiple="" tabindex="4">
                                                        {% for node in nodes_remain %}
                                                        <option value="{{ node.id }}" id="opt_{{ node.id }}" >{{ node }}</option>
                                                        {% endfor %}
                                                    </select>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan="2" class="no-borders">
                                                    <button type="button" class="btn btn-info btn-sm" id="btn-add-to-node">{% trans 'Confirm' %}</button>
                                                </td>
                                            </tr>
                                        </form>

                                        {% for node in system_user.nodes.all|sort %}
                                        <tr>
                                          <td ><b class="bdg_node" data-gid={{ node.id }}>{{ node }}</b></td>
                                          <td>
                                              <button class="btn btn-danger pull-right btn-xs btn-remove-from-node" type="button"><i class="fa fa-minus"></i></button>
                                          </td>
                                        </tr>
                                        {% endfor %}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% include 'assets/_asset_user_auth_modal.html' %}
{% endblock %}
{% block custom_foot_js %}
<script>
function initAssetsTable() {
    var connectivity = {{ system_user.connectivity | safe }};
    var options = {
		ele: $('#system_user_list'),
		buttons: [],
		order: [],
		columnDefs: [
			{targets: 0, createdCell: function (td, cellData, rowData) {
			    cellData = htmlEscape(cellData);
				var detail_btn = '<a href="{% url "assets:asset-detail" pk=DEFAULT_PK %}" data-aid="'+rowData.id+'">' + cellData + '</a>';
				$(td).html(detail_btn.replace('{{ DEFAULT_PK }}', rowData.id));
			}},
			{targets: 3, createdCell: function (td, cellData) {
				if (connectivity.unreachable.indexOf(cellData) >= 0) {
					$(td).html('<i class="fa fa-times text-danger"></i>')
				 } else if (connectivity.reachable.indexOf(cellData) >= 0 ) {
					$(td).html('<i class="fa fa-check text-navy"></i>')
				 } else {
                    $(td).html('')
                }
			}},
            {targets: 4, createdCell: function (td, cellData, rowData) {
                var push_btn = '';
                {% if system_user.auto_push %}
				push_btn = '<a class="btn btn-xs btn-primary btn-push-asset" data-uid="{{ DEFAULT_PK }}" >{% trans "Push" %}</a>'.replace("{{ DEFAULT_PK }}", cellData);
                {% endif %}
                var test_btn = ' <a class="btn btn-xs btn-info btn-test-asset" data-uid="{{ DEFAULT_PK }}" >{% trans "Test" %}</a>'.replace("{{ DEFAULT_PK }}", cellData);
                {#var unbound_btn = '<a class="btn btn-xs btn-danger m-l-xs btn-asset-unbound" data-uid="{{ DEFAULT_PK }}">{% trans "Unbound" %}</a>'.replace('{{ DEFAULT_PK }}', cellData);#}
                var update_auth_btn = ' <a class="btn btn-xs btn-primary btn-update-asset-user-auth" data-aid="{{ DEFAULT_PK }}" data-hostname="hostname777">{% trans "Update auth" %}</a>'.replace("{{ DEFAULT_PK }}", cellData).replace("hostname777", rowData.hostname);
                $(td).html(push_btn + test_btn + update_auth_btn);
			}}
		],
		ajax_url: '{% url "api-assets:system-user-assets" pk=system_user.id %}',
		columns: [{data: "hostname" }, {data: "ip" }, {data: "port" }, {data: "hostname" }, {data: "id"}],
		op_html: $('#actions').html()
	};
	jumpserver.initServerSideDataTable(options);
}

function updateSystemUserNode(nodes) {
    var the_url = "{% url 'api-assets:system-user-detail' pk=system_user.id %}";
    var body = {
        nodes: Object.assign([], nodes)
    };
    var success = function(data) {
        // remove all the selected groups from select > option and rendered ul element;
        $('.select2-selection__rendered').empty();
        $('#node_selected').val('');
        $.map(jumpserver.nodes_selected, function(node_name, index) {
            $('#opt_' + index).remove();
            // change tr html of user groups.
            $('.node_edit tbody').append(
                '<tr>' +
                '<td><b class="bdg_node" data-gid="' + index + '">' + node_name + '</b></td>' +
                '<td><button class="btn btn-danger btn-xs pull-right btn-remove-from-node" type="button"><i class="fa fa-minus"></i></button></td>' +
                '</tr>'
            )
        });
        // clear jumpserver.nodes_selected
        jumpserver.nodes_selected = {};
    };
    APIUpdateAttr({
        url: the_url,
        body: JSON.stringify(body),
        success: success
    });
}
jumpserver.nodes_selected = {};

function initAssetUserAuthModalForm(hostname, username){
    $('#id_hostname_p').html(hostname);
    $('#id_username_p').html(username);
    $('#id_password').parent().removeClass('has-error');
    $('#id_password').val('');
}

var assetId;

$(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];
    });
	initAssetsTable();
})
.on('click', '.btn-push', function () {
    var the_url = "{% url 'api-assets:system-user-push' pk=system_user.id %}";
    var error = function (data) {
        alert(data)
    };
    var success = function (data) {
        var task_id = data.task;
        var url = '{% url "ops:celery-task-log" pk=DEFAULT_PK %}'.replace("{{ DEFAULT_PK }}", task_id);
        window.open(url, '', 'width=800,height=600,left=400,top=400')
    };
    APIUpdateAttr({
        url: the_url,
        error: error,
        method: 'GET',
        success: success
    });
})
.on('click', '.btn-test-connective', function () {
    var the_url = "{% url 'api-assets:system-user-connective' pk=system_user.id %}";
    var error = function (data) {
        alert(data)
    };
    var success = function (data) {
        var task_id = data.task;
        var url = '{% url "ops:celery-task-log" pk=DEFAULT_PK %}'.replace("{{ DEFAULT_PK }}", task_id);
        window.open(url, '', 'width=800,height=600,left=400,top=400')
    };
    APIUpdateAttr({
        url: the_url,
        error: error,
        method: 'GET',
        success: success
    });
})
.on('click', '.btn-remove-from-node', function() {
    var $this = $(this);
    var $tr = $this.closest('tr');
    var $badge = $tr.find('.bdg_node');
    var gid = $badge.data('gid');
    var node_name = $badge.html() || $badge.text();
    $('#groups_selected').append(
        '<option value="' + gid + '" id="opt_' + gid + '">' + node_name + '</option>'
    );
    $tr.remove();
    var nodes = $('.bdg_node').map(function () {
        return $(this).data('gid');
    }).get();
    updateSystemUserNode(nodes);
})
.on('click', '#btn-add-to-node', function() {
    if (Object.keys(jumpserver.nodes_selected).length === 0) {
        return false;
    }
    var nodes = $('.bdg_node').map(function() {
        return $(this).data('gid');
    }).get();
    $.map(jumpserver.nodes_selected, function(value, index) {
        nodes.push(index);
    });
    updateSystemUserNode(nodes);
})
.on('click', '.btn-push-asset', function () {
    var $this = $(this);
    var asset_id = $this.data('uid');
    var the_url = "{% url 'api-assets:system-user-push-to-asset' pk=object.id aid=DEFAULT_PK %}";
    the_url = the_url.replace("{{ DEFAULT_PK }}", asset_id);
    var success = function (data) {
        var task_id = data.task;
        var url = '{% url "ops:celery-task-log" pk=DEFAULT_PK %}'.replace("{{ DEFAULT_PK }}", task_id);
        window.open(url, '', 'width=800,height=600,left=400,top=400')
    };
    var error = function (data) {
        alert(data)
    };
    APIUpdateAttr({
        url: the_url,
        method: 'GET',
        success: success,
        error: error
    })
})
.on('click', '.btn-test-asset', function () {
    var $this = $(this);
    var asset_id = $this.data('uid');
    var the_url = "{% url 'api-assets:system-user-test-to-asset' pk=object.id aid=DEFAULT_PK %}";
    the_url = the_url.replace("{{ DEFAULT_PK }}", asset_id);
    var success = function (data) {
        var task_id = data.task;
        var url = '{% url "ops:celery-task-log" pk=DEFAULT_PK %}'.replace("{{ DEFAULT_PK }}", task_id);
        window.open(url, '', 'width=800,height=600,left=400,top=400')
    };
    var error = function (data) {
        alert(data)
    };
    APIUpdateAttr({
        url: the_url,
        method: 'GET',
        success: success,
        error: error
    })
})
.on('click', '.btn-update-asset-user-auth', function() {
    assetId = $(this).data('aid');
    var hostname = $(this).data('hostname');
    var username = '{{ system_user.username }}';
    initAssetUserAuthModalForm(hostname, username);
    $("#asset_user_auth_modal").modal();
})
.on('click', '#btn_asset_user_auth_modal_confirm', function(){
    var password = $('#id_password').val();
    if (password){
        var data = {
            'name': "{{ system_user.username }}",
            'asset': assetId,
            'username': "{{ system_user.username }}",
            'password': password
        };
        formSubmit({
            data: data,
            url: "{% url 'api-assets:asset-user-list' %}",
            method: 'POST',
            success: function () {
                toastr.success("{% trans 'Update successfully!' %}");
            },
            error: function () {
                toastr.error("{% trans 'Update failed!' %}");
            }
        });
        $("#asset_user_auth_modal").modal('hide');
    }
    else{
        $('#id_password').parent().addClass('has-error');
    }
})
</script>
{% endblock %}
