/*** Firebase Cloud Messaging: https://firebase.google.com/ ***/
// [START get_messaging_object]
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
// [END get_messaging_object]
// [START set_public_vapid_key]
// Add the public key generated from the console here.
messaging.usePublicVapidKey('BBRqZmtVUlwC8RBxKpqHwnmBc82q6Xt3rlETq1kNblNk1kBjxxmWrwXCDxzb8lixieZqe74nI2BrmXaEP-OCyRk');
// [END set_public_vapid_key]
// [START refresh_token]
// Callback fired if Instance ID token is updated.
messaging.onTokenRefresh(() => 
{
	console.log('token refreshing...');
	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();
		// [END_EXCLUDE]
	}).catch((err) => 
	{
		console.log('Unable to retrieve refreshed token ', err);
	});
});
// [END refresh_token]

// [START receive_message]
// Handle incoming messages. Called when:
// - a message is received while the app has focus
// - the user clicks on an app notification created by a service worker
//   `messaging.setBackgroundMessageHandler` handler.
messaging.onMessage((payload) => 
{
	//console.log('Message received. ', payload);
	// [START_EXCLUDE]
	// Update the UI to include the received message.
	displayMessage(payload);
	// [END_EXCLUDE]
});
// [END receive_message]

function resetUI() 
{
	// [START get_token]
	// Get Instance ID token. Initially this makes a network call, once retrieved
	// subsequent calls to getToken will return from cache.
	messaging.getToken().then((currentToken) => 
	{
		if (currentToken)
		{
			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 actionTokenDB(currentToken, action)
{
	if (!isTokenSentToServer())
	{
		var data = {};
		data.action = action;
		data.fcm_key_id = currentToken;
		callModule('/lib/firebaseMessaging.php', data, function(){setTokenSentToServer(action)});
	} else console.log('Token already stored.');
}

// Send the Instance ID token your application server, so that it can:
// - send messages back to this app
// - subscribe/unsubscribe the token from topics
function sendTokenToServer(currentToken) 
{
	/**
	if (!isTokenSentToServer()) 
	{
		console.log('Sending token to server...', currentToken);
	} 
	else
	{
		console.log('Token already sent to server so won\'t send it again unless it changes', currentToken);
	}
	**/
	actionTokenDB(currentToken, 1);
}

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

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

function requestPermission() 
{
	// [START request_permission]
	Notification.requestPermission().then((permission) => 
	{
		if (permission === 'granted')
		{
			// TODO(developer): Retrieve an Instance ID token for use with FCM.
			// [START_EXCLUDE]
			// In many cases once an app has been granted notification permission,
			// it should update its UI reflecting this.
			resetUI();
			// [END_EXCLUDE]
		} 
		else 
		{
			console.log('Unable to get permission to notify.');
		}
	});
// [END request_permission]
}

function deleteToken()
{
	// Delete Instance ID token.
	// [START delete_token]
	messaging.getToken().then((currentToken) => 
	{
		messaging.deleteToken(currentToken).then(() => 
		{
			console.log('Delete token', currentToken);
			actionTokenDB(currentToken, 0);
			setTokenSentToServer(false);
			// [START_EXCLUDE]
			// Once token is deleted update UI.
			resetUI();
			// [END_EXCLUDE]
		}).catch((err) => 
		{
			console.log('Unable to delete token. ', err);
		});
	// [END delete_token]
	}).catch((err) => 
	{
		console.log('Error retrieving Instance ID token. ', err);
		//showToken('Error retrieving Instance ID token. ', err);
	});
}

// Add a message to the messages element.
function displayMessage(payload) 
{
	console.log(payload);
	var opts = 
	{
		body: payload.data.body, 
		icon: 'https://champ.jona.co.za/media/images/manifest_logo.png',
		badge: 'https://champ.jona.co.za/media/images/notification_badge.png', 
		vibrate:[100,50,100], 
		silent:false,
		data: { url:payload.data.click_action},
		actions: [{action: "open_url", title: "Open Now"}]									
	};	
	//runNotification(payload.msg.title, opts);
	navigator.serviceWorker.ready.then(function(registration){registration.showNotification(payload.data.title, opts);});
}

resetUI();