extendSidebar();

function navigate(url)
{
    window.location.href = window.location+'/'+url;
}

function extendSidebar()
{
    let foo = $('.nav-item.active');
    if (foo.attr('parent'))
    {
        $('#'+foo.attr('parent')).collapse('show');
        $('#link-'+foo.attr('parent')).addClass('active');
    }
}

function markNotificationAsRead(id)
{
    $.post('/api/notification/'+id+'/read?api_token='+api_token, function () {
        $('#'+id).removeClass('notification-success');
        $('#'+id).removeClass('cursor');
        $('#'+id).removeAttr('onclick');

        $('#notification-'+id).removeClass('notification-success');
        $('#notification-'+id).removeClass('cursor');
        $('#notification-'+id).removeAttr('onclick');
        updateNotificationNumber(-1);
    });
}

function markAllNotificationAsRead()
{
    $.get('/api/notification/allRead',{"api_token": api_token}, function (data) {
        $.each(data,function (key,value) {
            $('#'+value.id).removeClass('notification-success');
            $('#'+value.id).removeClass('cursor');
            $('#'+value.id).removeAttr('onclick');

            $('#notification-'+value.id).removeClass('notification-success');
            $('#notification-'+value.id).removeClass('cursor');
            $('#notification-'+value.id).removeAttr('onclick');
            updateNotificationNumber(-1);
        })
    });
}

function updateNotificationNumber(foo)
{
    span = $('#notification-number');
    if (parseInt(span.html())+parseInt(foo) == 0)
    {
        span.addClass('d-none');
    }
    else
    {
        span.removeClass('d-none');
    }
    span.html(parseInt(span.html())+parseInt(foo));
}

function addNotification(notification)
{
    let notificationcontainer = $("#notification-container");
    notificationcontainer.prepend(
        '<li id="'+notification.id+'" class="list-group-item cursor notification-success" style="border-bottom: solid 1px lightgrey" onclick="markNotificationAsRead(\''+notification.id+'\')" >\n' +
            '<div class="d-flex">' +
                '<div style="min-width: 2rem">\n' +
                    notification.icon +
                '</div>\n' +
                '<div>\n' +
                    '<b class="mb-1">'+notification.name+'</b>\n' +
                    '<p class="text-muted m-0">'+notification.msg+'</p>\n' +
                '</div>\n' +
            '</div>\n' +
        '</li>'
    );
    updateNotificationNumber(+1);
}