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 Received: " & Token)
	
	' Only save valid tokens (not empty, not "null", and reasonable length)
	If Token <> "" And Token <> "null" And Token.Length > 20 Then
		File.WriteString(File.DirInternal, "fcm_token.txt", Token)
		Log("Valid FCM token saved")
		
		' Immediately try to register with server in case we are already logged in
		CallSubDelayed(Main, "TryRegisterFCM")
	Else
		Log("Invalid FCM token received, not saving: " & Token)
	End If
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
		Dim token As String = File.ReadString(File.DirInternal, "fcm_token.txt")
		' Only return if it's a valid token (not "null" or empty)
		If token <> "" And token <> "null" And token.Length > 20 Then
			Return token
		End If
	End If
	Return ""
End Sub
