function notification_generator(reg, note) {

    var options = {
        body: note.content,
        icon: 'https://deutscher-fuersorgetag.de/wp-content/uploads/android-icon-72x72-1.png',
        vibrate: [100, 50, 100, 50, 100], //beep three times
//        vibrate: [500,110,500,110,450,110,200,110,170,40,450,110,200,110,170,40,500], //star wars
        data: {
            dateOfArrival: Date.now(),
            primaryKey: 1
        }
    };
    reg.showNotification(note.event, options);
}

//make push notifcation with data array
function checkPush(data) {
    //permission granted
    if (Notification.permission == 'granted') {
        navigator.serviceWorker.getRegistration().then(function(reg) {
            var i = 0;
            // Using an interval cause some browsers (including Firefox) are blocking notifications if there are too much in a certain time.
            var interval = window.setInterval(function () {
                // Thanks to the tag, we should only see the "Hi! 9" notification
                notification_generator(reg, data[i]);
                i++;
                if (i === data.length) {
                    window.clearInterval(interval);
                }
            }, 4000);
        });
    }
    //not denied and not granted -> ask for permission
    else if (Notification.permission !== "denied" && Notification.permission !== "granted") {
        Notification.requestPermission(function(result) {
            if (result === 'granted') {
                navigator.serviceWorker.ready.then(function(reg) {
                    var i = 0;
                    // Using an interval cause some browsers (including Firefox) are blocking notifications if there are too much in a certain time.
                    var interval = window.setInterval(function () {
                        // Thanks to the tag, we should only see the "Hi! 9" notification
                        notification_generator(reg, data[i]);
                        i++;
                        if (i === data.length) {
                            window.clearInterval(interval);
                        }
                    }, 4000);
                });
            }
        });
    }
}

navigator.serviceWorker.addEventListener('notificationclick', function(event) {
    const rootUrl = new URL('/', location).href;
    event.notification.close();
    event.waitUntil(
        clients.matchAll().then(matchedClients => {
            for (let client of matchedClients) {
                if(client.url.indexOf(rootUrl) >= 0) {
                    return client.focus();
                }
            }
            return clients.openWindow(rootUrl).then(function (client) {client.focus();});
        })
    );
});

jQuery(document).ready(function( $ ) {

    var unix = Math.round(+new Date()/1000);
    var postsOld;
    
    $.ajax({
        type: 'GET',
        url: self.location.origin + '/nachrichten?t='+unix,
        success: function (r) {
            postsOld = $(r).find('.category-pushnachricht').toArray();
        }
    });

    if(self.location.pathname == "/nachrichten/") {
        var interval;
        function myFunction() {
            interval = setInterval(alertFunc, 60000);
        }
        function alertFunc() {
            var unix = Math.round(+new Date()/1000);
            $.ajax({
                type: 'GET',
                url: self.location.origin + '/nachrichten?t='+unix,
                success: function (r) {
                    var postsNew = $(r).find('.category-pushnachricht').toArray();
                    postsOld = $(document).find('.category-pushnachricht').toArray();
                    var post = [];
                    for(var i = 0; i < postsOld.length; i++) {
                        var id = $(postsOld[i]).prop('id');
                        post[id] = [];
                        post[id]['post'] = postsOld[i];
                        post[id]['update'] = $(postsOld[i]).find('.updated').html();
                    }
                    var postUpdate = [];
                    var j = 0;
                    for(var i = 0; i < postsNew.length; i++) {
                        var id = $(postsNew[i]).prop('id');
                        var update = $(postsNew[i]).find('.updated').html();
                        //post exists and update is new
                        if ( (post[id] && post[id]['update'] != update) || (!post[id]) ) {
                            postUpdate[j] = [];
                            postUpdate[j]['post'] = postsNew[i];
                            postUpdate[j]['id'] = id;
                            j++;
                        }
                    }
                    for(var i = 0; i < postUpdate.length; i++) {
                        var found = $(document).find('#' + postUpdate[i]['id']);
                        if(found.length) {
                            found.replaceWith(postUpdate[i]['post']);
                        } else {
                            $('.fusion-posts-container').prepend( $(postUpdate[i]['post']) );
                        }
                    }
                }
            });
        }
        myFunction();
    } else {
        var interval;
        function myBubble() {
            interval = setInterval(alertBubble, 60000);
        }
        function alertBubble() {
            var unix = Math.round(+new Date()/1000);
            $.ajax({
                type: 'GET',
                url: self.location.origin + '/nachrichten?t='+unix,
                success: function (r) {
                    if(!postsOld) {
                        postsOld = $(r).find('.category-pushnachricht').toArray();
                    } else {
                        var postsNew = $(r).find('.category-pushnachricht').toArray();
                        var cNew = postsNew.length;
                        var cOld = postsOld.length;
                        if(cNew > cOld) {
                            for(var i = 0; i < cOld; i++) {
                                postsNew.pop();
                            }
                            //get new entry
                            var htmlNew = $(postsNew);
                            //set all entries to old state, await new entries in some seconds
                            postsOld = $(r).find('.category-pushnachricht').toArray();
                            //show buuble
                            $('#push-container a').html('');
                            $('#push-container a').html(htmlNew);
                            $('#push-container').fadeIn(500);
                            //show notification
                            var title = htmlNew.find('.entry-title').html();
                            var text = htmlNew.find('.fusion-post-content-container').html();
                            var textString = text.replace(/<p>(.*)<\/p>/g, "$1\n");
                            var date = htmlNew.find('.updated > span').html();
                            data = {
                                author: "Deutscher Fürsorgetag",
                                content: textString,
                                event: title,
                                link: "https://deutscher-fuersorgetag.de/nachrichten/",
                                start: date
                            };
                            checkPush([data]);
                        }
                    }
                }
            });

        }
        myBubble();

    }

    var interval2;
    function myBubble2() {
        interval2 = setInterval(alertBubble2, 60000);
    }
    function alertBubble2() {
        $.ajax({
            type: 'POST',
            url: bpcScriptRequest.ajaxurl,
            data: {
                action: 'serversidefunction',
                task: 'getUserNotifications'
            },
            success: function (r) {
                if(r.length) {
                    data = JSON.parse(r);
                    if(data) {
                        checkPush(data);
                    }
                }
            }
        });
    }
    myBubble2();
});




