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 and when it refreshes
Sub fm_TokenRefresh (Token As String)
	Log("FCM Token Received/Refreshed: " & Token)
	
	' Only save valid tokens (not empty, not "null", and reasonable length)
	If Token <> "" And Token <> "null" And Token.Length > 20 Then
		' Save the new token
		File.WriteString(File.DirInternal, "fcm_token.txt", Token)
		Log("Valid FCM token saved")
		
		' Save timestamp of when token was refreshed
		File.WriteString(File.DirInternal, "fcm_token_timestamp.txt", DateTime.Now)
		
		' Immediately re-register with server (critical for token expiration handling)
		CallSubDelayed(Main, "TryRegisterFCM")
		
		Log("Token auto-refresh: Re-registered with server")
	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")
		
		' Validate token before returning
		If token <> "" And token <> "null" And token.Length > 20 Then
			Return token
		End If
	End If
	Return ""
End Sub
