var msg = firebase.messaging();
msg.requestPermission()
    .then(function () {

        return msg.getToken();
    })
    .then(token => {
        console.log("Zugriff auf msg", token);
        updateUser(token);

    })
    .catch(err => {
        console.error("Msg Error: ", err);
    })


function updateUser(token) {
    firebase.auth().onAuthStateChanged(function (user) {
        if (user) {
            firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function (idtoken) {
                $.ajax({
                    type: "POST",
                    url: "/user",
                    data: {
                        idtoken: idtoken,
                        message_id: token
                    },
                    success() {
                        console.log("User updated");
                    },
                    error(err) {
                        console.error("Error: " + err);
                    }
                });
            }).catch((error) => console.error("Get id token client error: ", error));
        } else {
            console.log("Check Auth error", user)
        }
    });
}

msg.onMessage(payload => {
    const title = payload.data.title
    new Notification(title, {
        body: payload.data.body
    });
})