B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Service
Version=9.9
@EndOfDesignText@
#Region Service Attributes
	#StartAtBoot: True
	#ExcludeFromLibrary: True
#End Region

Sub Process_Globals
	Private fm As FirebaseMessaging
End Sub

Sub Service_Create
	fm.Initialize("fm")
	Log("FirebaseMessaging Initialized")
	' Sometimes subscribing to a topic forces the token to be generated/refreshed
	fm.SubscribeToTopic("all_parents")
End Sub

Sub Service_Start (StartingIntent As Intent)
	If fm.HandleIntent(StartingIntent) Then Return
End Sub

Sub Service_Destroy

End Sub

' This is where the token is received initially
Sub fm_TokenRefresh (Token As String)
	Log("FCM Token: " & Token)
	' Save token for later registration if user is logged in
	File.WriteString(File.DirInternal, "fcm_token.txt", Token)
	
	' Immediately try to register with server in case we are already logged in
	CallSubDelayed(Main, "TryRegisterFCM")
End Sub

' This is where messages are received while app is running
Sub fm_MessageArrived (Message As RemoteMessage)
	Log("Message arrived")
	
	Dim data As Map = Message.GetData
	Dim title As String = "BusTrack Alert"
	Dim body As String = "Status updated."
	
	' 1. Get from Data payload
	If data.ContainsKey("title") Then
		title = data.Get("title")
	End If
	
	If data.ContainsKey("body") Then
		body = data.Get("body")
	End If
	
	Log("Displaying Notification: " & title & " | " & body)
	
	Dim n As Notification
	' Standard initialization. You can set the channel name in newer B4A versions
	' by using a different ID/Name combination if needed.
	n.Initialize
	n.Icon = "icon"
	n.SetInfo(title, body, Main)
	n.Notify(1)
End Sub

Public Sub GetToken As String
	If File.Exists(File.DirInternal, "fcm_token.txt") Then
		Return File.ReadString(File.DirInternal, "fcm_token.txt")
	End If
	Return ""
End Sub
