var firebaseConfig = {
    apiKey: "AIzaSyCJ2C0uZNfh-ZZXm5a-TJzwXM0AatEIho8",
    authDomain: "clientbase-f7e6c.firebaseapp.com",
    projectId: "clientbase-f7e6c",
    storageBucket: "clientbase-f7e6c.appspot.com",
    messagingSenderId: "627317059869",
    appId: "1:627317059869:web:5e2376c95f2b5d28e1f1f4",
    measurementId: "G-PPPL5R4WDS"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//firebase.analytics();

const messaging = firebase.messaging();
messaging.usePublicVapidKey('BJkjzzFho68um86Kk-8zdU5mV_2NkLxva7GOlnhvmMcRC9DkorljR7goEeqDB0L1epqipjdsccmBasoGucVwtQE');

messaging.onTokenRefresh(() => {
    messaging.getToken().then((refreshedToken) => {
        // Indicate that the new Instance ID token has not yet been sent to the
        // app server.
        setTokenSentToServer(false);
        // Send Instance ID token to app server.
        sendTokenToServer(refreshedToken);
        // [START_EXCLUDE]
        // Display new Instance ID token and clear UI of all previous messages.
        resetUI();
    }).catch((err) => {
    });
});

function sendTokenToServer(currentToken) {
    if (!isTokenSentToServer()) {
        // TODO(developer): Send the current token to your server.
        setTokenSentToServer(true);
    } else {
        var subscribe = getCookie("subscribe");
        if (subscribe == undefined) {
            document.cookie = "push_token="+currentToken;
        }
    }
}

// [START get_token]
function resetUI() {
    // Получить токен идентификатора экземпляра. Первоначально это делает сетевой вызов, после получения последующие вызовы getToken будут возвращаться из кэша.
    messaging.getToken().then((currentToken) => {
        if (currentToken) {
            var subscribe = getCookie("subscribe");
            if (subscribe == undefined) {
                document.cookie = "push_token="+currentToken;
            }
            sendTokenToServer(currentToken);
        } else {
            setTokenSentToServer(false);
        }
    }).catch((err) => {
        setTokenSentToServer(false);
    });
}
// [END get_token]

function setTokenSentToServer(sent) {
    window.localStorage.setItem('sentToServer', sent ? '1' : '0');
}

function isTokenSentToServer() {
    return window.localStorage.getItem('sentToServer') === '1';
}

function getCookie(name) {
    var pair = document.cookie.split('; ').find(x => x.startsWith(name+'='));
    if (pair) {
        return pair.split('=')[1];
    }
}
resetUI();
