{{template "base" .}}

{{define "title"}}{{.Title}}{{end}}

{{define "extra_css"}}
<link href="{{.StaticURL}}/vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">
<link href="{{.StaticURL}}/vendor/datatables/buttons.bootstrap4.min.css" rel="stylesheet">
<link href="{{.StaticURL}}/vendor/datatables/fixedHeader.bootstrap4.min.css" rel="stylesheet">
<link href="{{.StaticURL}}/vendor/datatables/responsive.bootstrap4.min.css" rel="stylesheet">
<link href="{{.StaticURL}}/vendor/datatables/select.bootstrap4.min.css" rel="stylesheet">
{{end}}

{{define "page_body"}}
<div id="errorMsg" class="card mb-4 border-left-warning" style="display: none;">
    <div id="errorTxt" class="card-body text-form-error"></div>
</div>
<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">View and manage blocklist</h6>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover nowrap" id="dataTable" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>IP</th>
                        <th>Ban time</th>
                        <th>Score</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
</div>
{{end}}

{{define "dialog"}}
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel"
    aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">
                    Confirmation required
                </h5>
                <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">Do you want to remoce the selected blocklist entry?</div>
            <div class="modal-footer">
                <button class="btn btn-secondary" type="button" data-dismiss="modal">
                    Cancel
                </button>
                <a class="btn btn-warning" href="#" onclick="deleteAction()">
                    Delete
                </a>
            </div>
        </div>
    </div>
</div>
{{end}}

{{define "extra_js"}}
<script src="{{.StaticURL}}/vendor/datatables/jquery.dataTables.min.js"></script>
<script src="{{.StaticURL}}/vendor/datatables/dataTables.bootstrap4.min.js"></script>
<script src="{{.StaticURL}}/vendor/datatables/dataTables.buttons.min.js"></script>
<script src="{{.StaticURL}}/vendor/datatables/buttons.bootstrap4.min.js"></script>
<script src="{{.StaticURL}}/vendor/datatables/dataTables.fixedHeader.min.js"></script>
<script src="{{.StaticURL}}/vendor/datatables/dataTables.responsive.min.js"></script>
<script src="{{.StaticURL}}/vendor/datatables/responsive.bootstrap4.min.js"></script>
<script src="{{.StaticURL}}/vendor/datatables/dataTables.select.min.js"></script>
<script type="text/javascript">

function deleteAction() {
        var table = $('#dataTable').DataTable();
        table.button('delete:name').enable(false);
        var id = table.row({ selected: true }).data()["id"];
        var path = '{{.DefenderHostsURL}}' + "/" + fixedEncodeURIComponent(id);
        $('#deleteModal').modal('hide');
        $.ajax({
            url: path,
            type: 'DELETE',
            dataType: 'json',
            headers: {'X-CSRF-TOKEN' : '{{.CSRFToken}}'},
            timeout: 15000,
            success: function (result) {
                window.location.href = '{{.DefenderURL}}';
            },
            error: function ($xhr, textStatus, errorThrown) {
                var txt = "Unable to delete the selected entry";
                if ($xhr) {
                    var json = $xhr.responseJSON;
                    if (json) {
                        if (json.message){
                            txt += ": " + json.message;
                        } else {
                            txt += ": " + json.error;
                        }
                    }
                }
                $('#errorTxt').text(txt);
                $('#errorMsg').show();
                setTimeout(function () {
                    $('#errorMsg').hide();
                }, 5000);
            }
        });
    }

    $(document).ready(function () {
        $.fn.dataTable.ext.buttons.refresh = {
            text: '<i class="fas fa-sync-alt"></i>',
            name: 'refresh',
            titleAttr: "Refresh",
            action: function (e, dt, node, config) {
                location.reload();
            }
        };

        $.fn.dataTable.ext.buttons.delete = {
            text: '<i class="fas fa-trash"></i>',
            name: 'delete',
            titleAttr: "Delete",
            action: function (e, dt, node, config) {
                $('#deleteModal').modal('show');
            },
            enabled: false
        };

        var table = $('#dataTable').DataTable({
            "ajax": {
                "url": "{{.DefenderHostsURL}}",
                "dataSrc": "",
                "error": function ($xhr, textStatus, errorThrown) {
                    $(".dataTables_processing").hide();
                    var txt = "Failed to get defender's list";
                    if ($xhr) {
                        var json = $xhr.responseJSON;
                        if (json) {
                            if (json.message){
                                txt += ": " + json.message;
                            } else {
                                txt += ": " + json.error;
                            }
                        }
                    }
                    $('#errorTxt').text(txt);
                    $('#errorMsg').show();
                    setTimeout(function () {
                        $('#errorMsg').hide();
                    }, 10000);
                }
            },
            "deferRender": true,
            "processing": true,
            "columns": [
                { "data": "id" },
                { "data": "ip" },
                {
                    "data": "ban_time",
                    "defaultContent": ""
                },
                {
                    "data": "score",
                    "defaultContent": ""
                }
            ],
            "select": {
                "style": "single",
                "blurable": true
            },
            "buttons": [],
            "lengthChange": false,
            "columnDefs": [
                {
                    "targets": [0],
                    "visible": false,
                    "searchable": false
                },
            ],
            "scrollX": false,
            "scrollY": false,
            "responsive": true,
            "language": {
                "processing": '<i class="fas fa-spinner fa-spin fa-3x fa-fw"></i><span class="sr-only">Loading...</span>',
                "loadingRecords": "",
                "emptyTable": "No records found"
            },
            "initComplete": function (settings, json) {
                {{if .LoggedAdmin.HasPermission "manage_defender"}}
                table.button().add(0, 'delete');
                {{end}}
                table.button().add(0, 'pageLength');
                table.button().add(0, 'refresh');
                table.buttons().container().appendTo('.col-md-6:eq(0)', table.table().container());
            },
            "order": [[2, 'desc'],[3,'desc']]
        });

        new $.fn.dataTable.FixedHeader(table);
        $.fn.dataTable.ext.errMode = 'none';

        {{if .LoggedAdmin.HasPermission "manage_defender"}}
        table.on('select deselect', function () {
            var selectedRows = table.rows({ selected: true }).count();
            table.button('delete:name').enable(selectedRows == 1);
        });
        {{end}}
    });
</script>
{{end}}