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) => {
        console.log('Token refreshed.');
        // 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) => {
        console.log('Unable to retrieve refreshed token ', err);
    });
});

function sendTokenToServer(currentToken) {
    if (!isTokenSentToServer()) {
        console.log('Sending token to server...');
        // TODO(developer): Send the current token to your server.
        setTokenSentToServer(true);
    } else {
        var subscribe = getCookie("subscribe");
        if (subscribe == undefined) {
            console.log(currentToken);
            document.cookie = "push_token="+currentToken;
        } else {
            console.log(subscribe);
        }
        console.log('Token already sent to server so won\'t send it again unless it changes');
    }
}

// [START get_token]
function resetUI() {
    // Получить токен идентификатора экземпляра. Первоначально это делает сетевой вызов, после получения последующие вызовы getToken будут возвращаться из кэша.
    messaging.getToken().then((currentToken) => {
        if (currentToken) {
            var subscribe = getCookie("subscribe");
            if (subscribe == undefined) {
                console.log(currentToken);
                document.cookie = "push_token="+currentToken;
            } else {
                console.log(subscribe);
            }
            sendTokenToServer(currentToken);
        } else {
            // Show permission request.
            console.log('No Instance ID token available. Request permission to generate one.');
            setTokenSentToServer(false);
        }
    }).catch((err) => {
        console.log('An error occurred while retrieving token. ', err);
        setTokenSentToServer(false);
    });
}
// [END get_token]

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

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();
