var config = {
    apiKey: "AIzaSyCSJEE0x8OixMO3vGa0PlZ6s91L0ZHrdZE",
    authDomain: "api-push-71b6e.firebaseapp.com",
    databaseURL: "https://api-push-71b6e.firebaseio.com",
    projectId: "api-push-71b6e",
    storageBucket: "api-push-71b6e.appspot.com",
    messagingSenderId: "998157547773"
};

firebase.initializeApp(config);

const messaging = firebase.messaging();

$(document).ready(function () {
    requestPermission();
});

//        const messaging = firebase.messaging();
messaging.usePublicVapidKey('BMEXNPyv2XetB_1dqyt2iAF88KI7uJ5mhNC1OP3TAliNucEe-NWcMKgoW53vzZJBR3_xCEF9xm-PHfFjkphuF6Q');

messaging.getToken().then(function (currentToken) {
    if (currentToken) {
        console.log("Get Token", currentToken)
        sendTokenToServer(currentToken);
    } else {
        console.log('No Instance ID token available. Request permission to generate one.');
        setTokenSentToServer(false);
    }
}).catch(function (err) {
    console.log('An error occurred while retrieving token. ', err);
    showToken('Error retrieving Instance ID token. ', err);
    setTokenSentToServer(false);
});

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

messaging.onMessage(function (payload) {
    console.log('Received message ', payload);
    notificationTitle = payload.data.title,
            notificationOptions = {
                body: payload.data.body,
                icon: payload.data.icon,
            };
    var notification = new Notification(notificationTitle, notificationOptions);
    $(".target").append("<p>" + notificationTitle + "<br>" + payload.data.body + "</p>");
});

function showToken(currentToken) {
    console.log("Current token", currentToken)
}

function sendTokenToServer(currentToken) {
//    if (!isTokenSentToServer()) {
        console.log('Sending token to server...');
        $.ajax({
            type: "POST",
            url: url_envio,
            data: {token: currentToken},
            success: function (data) {
                setTokenSentToServer(true);
                //$('#divizinea').append(data);//COMENTAR ISSO DEPOIS
                //console.log('data:'+data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log('errror:' + textStatus + '\n' + errorThrown);
            }
        });

//    } else {
  //      console.log('Token already sent to server so won\'t send it again ' +
    //            'unless it changes');
//    }
}

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

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


function requestPermission() {
    console.log('Requesting permission...');
    messaging.requestPermission().then(function () {

        messaging.getToken().then(function (currentToken) {
            if (currentToken) {
                sendTokenToServer(currentToken);
            } else {
                console.log('No Instance ID token available. Request permission to generate one.');
                setTokenSentToServer(false);
            }
        }).catch(function (err) {
            console.log('An error occurred while retrieving token. ', err);
            showToken('Error retrieving Instance ID token. ', err);
            setTokenSentToServer(false);
        });
        console.log('Notification permission granted.');
    }).catch(function (err) {
        console.log('Unable to get permission to notify.', err);
        //AJAX AQUI
    });
}
