$(document).ready(function () {
    $.getJSON("/api/urls/vessels/datatable/")
        .done(function (data) {
            AjaxDatatableViewUtils.initialize_table(
                $('#datatable_vessels'),
                data,
            );
        });
});

function deleteVessel(row) {
    id = row.closest('tr').id.substr(4);
    $.getJSON("/api/urls/vessels/delete/" + id + "/")
        .done(function (data) {
            window.location.href = data;
        });
}

function editVessel(row) {
    id = row.closest('tr').id.substr(4);
    $.getJSON("/api/urls/vessels/edit/" + id + "/")
        .done(function (data) {
            window.location.href = data;
        });
}

function locateVessel(row) {
    id = row.closest('tr').id.substr(4);
    $.getJSON("/api/vessels/location/" + id + "/")
        .done(function (data) {
            if (data["status"] == "success") {
                $('#locationModal .modal-body').html('<div id="map"></div>');
                $('#locationModalLabel').text("Location of " + data["name"]);
                $('#map').css('height', '400px');
                $.getJSON("/api/urls/static/?file=" + encodeURIComponent("core/dist/images/"))
                    .done(function (data2) {
                        L.Icon.Default.prototype.options.imagePath = data2;
                        var map = L.map('map').setView([data["location"]["latitude"], data["location"]["longitude"]], 8);
                        L.tileLayer('https://tileserver.kumi.systems/{z}/{x}/{y}.png', {
                            maxZoom: 19,
                            attribution: '© OpenStreetMap'
                        }).addTo(map);
                        var marker = L.marker([data["location"]["latitude"], data["location"]["longitude"]]).addTo(map);
                        marker.bindPopup("<b>" + data["name"] + "</b><br>En route to " + data["destination"] + ".").openPopup();
                        $('#locationModal').modal('show');
                        setTimeout(function () {
                            window.dispatchEvent(new Event('resize'));
                        }, 1000);
                    })
            } else {
                $('#locationModal .modal-body').html("<strong>" + data["error"] + "</strong>");
            }
        });
}