$(function () {
    if (typeof firebase !== 'undefined' && typeof firebaseConfig !== 'undefined' && typeof navigator !== 'undefined' && navigator.serviceWorker !== undefined) {
        firebase.initializeApp(firebaseConfig);

        const messaging = firebase.messaging();
        messaging.onMessage(function (payload) {
            //console.log('onMessage->', payload);        
            var ls = localStorage.getItem(payload.messageId);
            if (!ls) {
                localStorage.setItem(payload.messageId, 'messaging');
                navigator.serviceWorker.register("/firebase-messaging-sw.js", { scope: "/firebase-cloud-messaging-push-scope" }).then((reg) => {
                    reg.showNotification(payload.notification.title, { body: payload.notification.body, icon: '/favicon.ico' });
                });
            }
            setTimeout(function () { localStorage.removeItem(payload.messageId) }, 5000);
        });
        navigator.serviceWorker.register("/firebase-messaging-sw.js", { scope: "/firebase-cloud-messaging-push-scope" }).then((reg) => {
            messaging
                .getToken()
                .then(function (token) {
                    var firebaseOldMessageToken = localStorage.getItem("firebaseMessageToken");
                    if (firebaseOldMessageToken != token) {
                        localStorage.setItem("firebaseMessageToken", token);
                        $.ajax({
                            type: 'POST',
                            url: base + 'api/token',
                            data: JSON.stringify({ token: token, OldToken: firebaseOldMessageToken, DeviceType: "web" }),
                            success: function (data) { console.log('data: ' + data); },
                            contentType: "application/json",
                            dataType: 'json'
                        });
                    }
                })
                .catch(function (err) {
                   // console.log("Unable to get permission to notify.", err);
                });
        });
    }
});
