var portfolioMessaging;

const getNotificationCookieName = function() {
    if (typeof MESSAGING_CONFIG.popup != 'undefined' && typeof MESSAGING_CONFIG.popup.cookie != 'undefined') {
        return MESSAGING_CONFIG.popup.cookie;
    }
    return 'showNotificationPopup';
};

const getNotificationCookie = function() {
    var cookieName    = getNotificationCookieName() + '=';
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(cookieName) == 0) {
            return c.substring(cookieName.length, c.length);
        }
    }
    return "";
};

const dismissNotificationPopup = function() {
    var expireDate = new Date();
    expireDate.setTime(expireDate.getTime() + 86400000);
    document.cookie = getNotificationCookieName() + "=false; expires=" + expireDate.toUTCString();
    $('.notification-popup').remove();
    notificationExists = 0;
};

const showNotificationPopup = function() {
    if (typeof MESSAGING_CONFIG.popup == 'undefined') {
        return requestPermission();
    }
    var popup = $('<div class="notification-popup"><div class="content"></div></div>').appendTo('body');
    $('<a class="close" href="#"><i class="icon-close"></i></a>')
        .click(function(){
            dismissNotificationPopup()
        })
        .appendTo(popup);
    $('.content', popup).html('<div class="d-flex">' +
                            '<div class="notif-logo"><img src="' + MESSAGING_CONFIG.popup.icon + '"></div>'+
                            '<div class="notif-body"><div class="notif-text">' + MESSAGING_CONFIG.popup.body + '</div></div>');
    $('<div class="notif-btns"></div>').appendTo('.notif-body', popup);
    $('<a class="allow btn btn-primary" href="#">' + MESSAGING_CONFIG.popup.allow + '</a>')
        .click(function(){
            requestPermission();
            dismissNotificationPopup();
        })
        .appendTo('.notif-btns', popup);
    $('<a class="dismiss btn btn-secondary" href="#">' + MESSAGING_CONFIG.popup.dismiss + '</a>')
    .click(function(){
        dismissNotificationPopup();
    })
    .appendTo('.notif-btns', popup);
    notificationExists = 1;
};

const getTokenKey = function() {
    if (typeof MESSAGING_CONFIG.tokenKey == 'undefined') {
        return 'NewsPushToken';
    }
    return MESSAGING_CONFIG.tokenKey;
};

const setTokenSentToServer = function(currentToken) {
    window.localStorage.setItem(getTokenKey(), currentToken);
};

const sendTokenToServer = function(currentToken) {
    if (isTokenSentToServer(currentToken)) {
        return console.log('Token already sent to server so won\'t send it again unless it changes');
    }
    console.log('Sending token to server...');
    var postData = {
        token: currentToken
    };
    if (typeof MESSAGING_CONFIG.project != 'undefined') {
        postData.project = MESSAGING_CONFIG.project;
    }
    if (typeof MESSAGING_CONFIG.topic != 'undefined') {
        postData.topic = MESSAGING_CONFIG.topic;
    }
    $.ajax({
        url    : getPushURL('/subscribe'),
        method : 'POST',
        cache  : false,
        data   : postData,
        success: function() {
            setTokenSentToServer(currentToken);
        }
    });
};

const isTokenSentToServer = function(currentToken) {
    return window.localStorage.getItem(getTokenKey()) === currentToken;
};

const getPushURL = function(action) {
    if (typeof MESSAGING_CONFIG.pushURL != 'undefined') {
        return MESSAGING_CONFIG.pushURL + action;
    }
    return 'https://p.portfolio.hu' + action;
};

const requestPermission = function() {
    portfolioMessaging.requestPermission().then(function() {
        console.log('Notification permission granted.');
        portfolioMessaging.getToken().then(function(refreshedToken) {
            sendTokenToServer(refreshedToken);
        })
    }).catch(function(err) {
        console.log('Unable to get permission to notify.', err);
    });
};

const unsubscribeUser = function() {
    portfolioMessaging.deleteToken(userToken)
        .then(function() {
            $.post(getPushURL('/unsubscribe'), { token: currentToken });
            setTokenSentToServer(null);
        })
        .catch(function(err) {
            console.log('Error unsubscribing', err)
        });
};

const invokeNotificationHandler = function() {
    if (!("Notification" in window)) {
        console.error("Browser does not support Notification");
        return;
    }
    if (Notification.permission === "granted") {
        requestPermission();
    } else
    if (Notification.permission === "default" && getNotificationCookie() != "false") {
        showNotificationPopup();
    }
};

if (typeof MESSAGING_CONFIG != 'undefined') {
    try {
        firebase.initializeApp(MESSAGING_CONFIG.firebase_config);
        firebase.analytics();

        portfolioMessaging = firebase.messaging();
        portfolioMessaging.usePublicVapidKey(MESSAGING_CONFIG.vapidKey);

        portfolioMessaging.onTokenRefresh(function () {
            portfolioMessaging.getToken().then(function (refreshedToken) {
                console.log('Token refreshed.');
                setTokenSentToServer(null);
                sendTokenToServer(refreshedToken);
            }).catch(function (err) {
                console.log('Unable to retrieve refreshed token ', err);
            });
        });

        portfolioMessaging.onMessage(function (payload) {
            new Notification(payload.notification.title, payload.notification);
        });

        $(function(){
            if (typeof WAIVE_NOTIFICATION == 'undefined') {
                invokeNotificationHandler();
            }
        });
    } catch (ex) {
        console.error('Messaging not supported');
        console.error(ex);
    }
}