{% extends '_base_list.html' %}
{% load i18n %}
{% load static %}
{% load terminal_tags %}
{% load common_tags %}
{% block custom_head_css_js %}
    <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>
{% endblock %}

{% block content_left_head %}
{% endblock %}

{% block table_pagination %}
{% endblock %}

{% block table_search %}
{% endblock %}

{% block table_container %}
    <table class="table table-striped table-bordered table-hover" id="session_table" data-page="false" >
        <thead>
        <tr>
            <th class="text-center"></th>
            <th class="text-center">{% trans 'ID' %}</th>
            <th class="text-center">{% trans 'User' %}</th>
            <th class="text-center">{% trans 'Database' %}</th>
            <th class="text-center">{% trans 'Database host' %}</th>
            <th class="text-center">{% trans 'Database user' %}</th>
            <th class="text-center">{% trans 'Database name' %}</th>
            <th class="text-center">{% trans 'Remote addr' %}</th>
            <th class="text-center">{% trans 'Login from' %}</th>
            <th class="text-center">{% trans 'Command' %}</th>
            <th class="text-center">{% trans 'Date start' %}</th>
            <th class="text-center">{% trans 'Duration' %}</th>
            <th class="text-center">{% trans 'Action' %}</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>

    <div class="hide" id="daterange">
        <div class="form-group p-l-5" id="date" style="padding-left: 5px">
            <div class="input-daterange input-group p-l-5" id="datepicker">
                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                <input type="text" class="input-sm form-control" style="width: 100px;" id="date_from" name="date_from" value="{{ date_from|date:'Y-m-d' }}">
                <span class="input-group-addon">to</span>
                <input type="text" class="input-sm form-control" style="width: 100px;" id="date_to" name="date_to" value="{{ date_to|date:'Y-m-d' }}">
            </div>
        </div>
    </div>

    <ul class="dropdown-menu search-help">
        <li><a class="search-item" data-value="user">{% trans 'User' %}</a></li>
        <li><a class="search-item" data-value="database">{% trans 'Database' %}</a></li>
        <li><a class="search-item" data-value="db_host">{% trans 'Database host' %}</a></li>
        <li><a class="search-item" data-value="db_user">{% trans 'Database user' %}</a></li>
        <li><a class="search-item" data-value="db_name">{% trans 'Database name' %}</a></li>
        <li><a class="search-item" data-value="remote_addr">{% trans 'Remote addr' %}</a></li>
    </ul>
{% endblock %}


{% block custom_foot_js %}
<script src="{% static 'js/plugins/datepicker/bootstrap-datepicker.js' %}"></script>
<script src="{% static 'js/plugins/datepicker/bootstrap-datepicker.zh-CN.min.js' %}" ></script>
<script>

function terminateSession(data) {
    function success() {
        window.setTimeout(function () {
            window.location.reload()
        }, 1000)
    }
    var success_message = '{% trans "Terminate task send, waiting ..." %}';
    var the_url = "{% url 'api-terminal:kill-session' %}";
    requestApi({
        url: the_url,
        method: 'POST',
        body: JSON.stringify(data),
        success: success,
        success_message: success_message
    });
}

var sessionListUrl = "{% url 'api-terminal:database-session-list' %}?is_finished={% if type == "online" %}0{% else %}1{% endif %}";
var dateFrom = "{{ date_from.timestamp }}";
var dateTo = "{{ date_to.timestamp }}";

function initTable() {
    dateFrom = toSafeDateISOStr(dateFrom * 1000);
    dateTo = toSafeDateISOStr(dateTo * 1000);
    sessionListUrl = setUrlParam(sessionListUrl, "date_from", dateFrom);
    sessionListUrl = setUrlParam(sessionListUrl, "date_to", dateTo);
    var options = {
        ele: $('#session_table'),
        ordering: false,
        columnDefs: [
            {targets: 1, createdCell: function (td, cellData, rowData, i) {
                var index = i + 1;
                var data = '<a href="{% url 'terminal:database-session-detail' pk=DEFAULT_PK %}">'
                    + index + "</a>";
                data = data.replace("{{ DEFAULT_PK }}", cellData);
                $(td).html(data);
            }},
            {targets: 2, createdCell: function (td, cellData) {
                var data = htmlEscape(cellData);
                $(td).html(data);
            }},
            {targets: 3, createdCell: function (td, cellData) {
                var data = htmlEscape(cellData);
                $(td).html(data);
            }},
            {targets: 4, createdCell: function (td, cellData) {
                var data = htmlEscape(cellData);
                $(td).html(data);
            }},
            {targets: 5, createdCell: function (td, cellData) {
                    var data = htmlEscape(cellData);
                    $(td).html(data);
                }},
            {targets: 6, createdCell: function (td, cellData) {
                var data = htmlEscape(cellData);
                $(td).html(data);
            }},
            {targets: 11, createdCell: function (td, cellData, rowData) {
                var data = "";
                if (cellData && rowData.date_start) {
                    data = timeOffset(rowData.date_start, cellData)
                }
                $(td).html(data);
            }},
            {targets: 12, createdCell: function (td, cellData, rowData) {
                var btnGroup = "";
                var replayBtn = '<a disabled data-session="sessionID" class="btn btn-xs btn-warning btn-replay" >{% trans "Replay" %}</a>';
                replayBtn = replayBtn.replace("sessionID", rowData.id);
                if (rowData.can_replay) {
                    replayBtn = replayBtn.replace("disabled", "")
                }
                var termBtn = '<a class="btn btn-xs btn-danger btn-term" disabled value="sessionID" terminal="terminalID" >{% trans "Terminate" %}</a>';
                if ("{{ request.user.is_org_admin }}" === "True") {
                    termBtn = termBtn.replace("disabled", "")
                        .replace("sessionID", cellData)
                        .replace("terminalID", rowData.terminal)
                }
                if (rowData.is_finished) {
                    btnGroup += replayBtn
                } else {
                    btnGroup += termBtn;
                }
                $(td).html(btnGroup);
            }}
        ],
        ajax_url: sessionListUrl,
        columns: [
            {data: "id"},
            {data: "id", orderable:false},
            {data: "user"},
            {data: "database"},
            {data: "db_host"},
            {data: "db_user"},
            {data: "db_name"},
            {data: "remote_addr"},
            {data: "login_from_display", orderable:false},
            {data: "command_amount", orderable:false},
            {data: "date_start"},
            {data: "date_end", orderable:false},
            {data: "id",orderable:false}
        ],
        op_html: $('#actions').html(),
        fb_html: $("#daterange").html()
    };
    table = jumpserver.initServerSideDataTable(options);
    return table
}

var table;
$(document).ready(function() {
    table = initTable("#session_table").on('init', function () {
        var dateFromRef = $("#date_from");
        var dateToRef = $("#date_to");
        var options = {
            format: "yyyy-mm-dd",
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: true,
            autoclose: true,
            language: navigator.language || "en",
        };
        dateFromRef.datepicker(options).on("changeDate", function () {
            if (!$(this).val()) {
                return
            }
            var value = $(this).val() + ' 0:0:0';
            var date = toSafeDateISOStr(value);
            var url = table.ajax.url();
            url = setUrlParam(url, "date_from", date);
            table.ajax.url(url);
            table.ajax.reload();
        });
        dateToRef.datepicker(options).on("changeDate", function () {
            if (!$(this).val()) {
                return
            }
            var value = $(this).val() + ' 23:59:59';
            var date = toSafeDateISOStr(value);
            var url = table.ajax.url();
            url = setUrlParam(url, "date_to", date);
            table.ajax.url(url);
            table.ajax.reload();
        });
    });

}).on('click', '.btn-term', function () {
    var $this = $(this);
    var session_id = $this.attr('value');
    var data = [
        session_id
    ];
    terminateSession(data)
}).on('click', '.btn-replay', function () {
    var sessionID = $(this).data("session");
    var replayUrl = "/luna/replay/" + sessionID;
    window.open(replayUrl, "height=600, width=800, top=400, left=400, toolbar=no, menubar=no, scrollbars=no, location=no, status=no");
}).on("click", '#session_table_filter input', function (e) {
    e.preventDefault();
    e.stopPropagation();
    var offset1 = $('#session_table_filter input').offset();
    var x = offset1.left;
    var y = offset1.top;
    var offset = $(".search-help").parent().offset();
    x -= offset.left;
    y -= offset.top;
    x += 18;
    y += 80;
    $('.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 keyword = $("#session_table_filter input");
    var value = $(this).data('value');
    var old_value = keyword.val();
    var new_value = old_value + ' ' + value + ':';
    keyword.val(new_value.trim());
    $('.dropdown-menu.search-help').hide();
    keyword.focus()
})
.on('click', 'body', function (e) {
    $('.dropdown-menu.search-help').hide()
})
</script>
{% endblock %}

