B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Service
Version=10.2
@EndOfDesignText@
'///////////////////////////////////////////////////////////////////////////////////////
'///  Agregar estas lineas al editor de manifiestos
'
'	CreateResourceFromFile(Macro, FirebaseAnalytics.GooglePlayBase)
'	CreateResourceFromFile(Macro, FirebaseAnalytics.Firebase)
'	CreateResourceFromFile(Macro, FirebaseAnalytics.FirebaseAnalytics)
'	CreateResourceFromFile(Macro, FirebaseNotifications.FirebaseNotifications)
'
'/// Agregar modulo de servicio nuevo FirebaseMessaging y copiar este modulo
'
'/// Bajar el archivo google-services.json de la consola de Firebase (https://console.firebase.google.com/)
'/// El nombre de la app en el archivo json tiene que ser el mismo que el nombre del paquete (Proyecto/Conf de Compilacion/Paquete)
'
'/// En Starter agregar esta linea
'
'	Sub Service_Create
'		CallSubDelayed(FirebaseMessaging, "SubscribeToTopics")
'	End Sub
'
'/// En Main en Sub Process_Globals agregar esta linea
'
'    Private const API_KEY As String = "AAAAv__xxxxxxxxxxxxx-xxxxxxxxxxxxxx-xxxxxxxxxxxx"
'
'/// Esta llave se consigue igualmente en la consola de Firebase, configuracion de proyecto, Cloud Messaging,
'/// es la clave de servidor.
'/// 
'/// Se necesitan agregar las librerías: FirebaseAnalitics, FirebaseNotifications, JSON y OkHttpUtils2
'///  ... JSON es necesario si se van a enviar mensajes, si solo se van a recibir, no es necesario.
'
'///////////////////////////////////////////////////////////////////////////////////////

Sub Process_Globals
'	Private fm As FirebaseMessaging
	Private const API_KEY As String = "AAAAv1qt3Lk:APA91bECIR-pHn6ul53eYyoVlpPuOo85RO-0zcAgEXwE7vqw8DFSbBtCaCINiqWQAkBBZXxHtQMdpU6B-jHIqgFKVL196UgwHv0Gw6_IgmipfV_NiItjzlH9d2QNpGLp9y_JUKVjUEhP" 'Api_Key cheveguerra@gmail.com/Pusher
	Dim locRequest As String
'	Dim phn As Phone
	Dim pe As PhoneEvents
	Dim c As Cursor
	Public GZip As GZipStrings
	Dim Sprvsr As String = "Sprv-Cedex" ' El topico al que se mandan los mensajes push
	Dim Subscrito As String
	Dim au As String 'ignore
End Sub

Sub Service_Create
'	fm.Initialize("fm") 'Inicializamos FirebaseMessaging
	pe.Initialize("pe") 'Para obtener la bateria
End Sub

Public Sub SubscribeToTopics
'	fm.SubscribeToTopic("Trckr") 'Topico general Keymon
	fm.SubscribeToTopic("Trckr") 'Tracker Global
'	Log("Suscrito al tracker global")
	fm.SubscribeToTopic("Trckr-Cedex") 'Topico de Guna
	If "Cdx_"&B4XPages.MainPage.usuario <> Subscrito Then
		fm.SubscribeToTopic("Cdx_"&B4XPages.MainPage.usuario) 'Propio (you can subscribe to more topics)
		fm.UnsubscribeFromTopic(Subscrito) 'Unsubscribe from topic
	End If
'	Log("Subscrito a "&"Cdx_"&B4XPages.MainPage.usuario)
	Subscrito = "Cdx_"&B4XPages.MainPage.usuario
'	Log(fm.token)
'	fm.UnsubscribeFromTopic("Sprvsr") 'Unsubscribe from topic
End Sub

Sub Service_Start (StartingIntent As Intent)
	If StartingIntent.IsInitialized Then fm.HandleIntent(StartingIntent)
	Sleep(0)
	Service.StopAutomaticForeground 'remove if not using B4A v8+.
	StartServiceAt(Me, DateTime.Now + 15 * DateTime.TicksPerMinute, True) 'Iniciamos servicio cada XX minutos
End Sub

Sub fm_MessageArrived (Message As RemoteMessage)
	Log("Message arrived")
	Log($"Message data: ${Message.GetData}"$)
'	getPhnId
	If Message.GetData.ContainsKey("t") Then
		Dim tipos As List = Regex.Split(",",Message.GetData.Get("t"))
		If tipos.IndexOf("pu") <> -1 Or tipos.IndexOf("au") <> -1 Then 'Si es una peticion de ubicacion
			Log("Es una peticion de ubicacion")
			locRequest="Activa"
			Log("Llamamos StartFLPSmall")
			CallSubDelayed(Tracker, "StartFLPSmall")
			CallSubDelayed(Tracker, "StartFLP")
		End If
		If tipos.IndexOf("au") <> -1 Then 'Si es una actualizacion de ubicacion
			au = 1
		End If
		If tipos.IndexOf("ping") <> -1 Then 'Si es un ping
			Log("Es un ping")
			Log("Mandamos pong")
			Dim params As Map = CreateMap("topic":Sprvsr,"title":"pong", "body":B4XPages.MainPage.usuario&" - Recibi mensaje "&Message.GetData.Get("title"), "t":"pong")
			SendMessage(params)
		End If
		If tipos.IndexOf("bgps") <> -1 Then 'Si es una instruccion de borrar archivo gps
			Log("Es una instruccion de borrar archivo gps")
			Log("Borramos archivo gps")
			borramosArchivoGPS
		End If
		If tipos.IndexOf("dr") <> -1 Then 'Si es una peticion de ruta gps
			Log("Es una peticion de Ruta GPS")
			Dim rutaGpsCmp As String = dameRuta
			Dim params As Map = CreateMap("topic":Sprvsr,"title":"ruta", "body":B4XPages.MainPage.usuario&" - Recibi mensaje "&Message.GetData.Get("title"), "t":"ruta", "r":rutaGpsCmp)
			SendMessage(params)
		End If
		If tipos.IndexOf("bgps2") <> -1 Then 'Si es una instruccion de borrar DB gps
			Log("Es una instruccion de borrar BD gps")
			Log("Borramos BD gps")
			borraGPSHist
		End If
		If tipos.IndexOf("pu") = -1 And tipos.IndexOf("au") = -1 And tipos.IndexOf("ping") = -1 And tipos.IndexOf("dr") = -1  Then
			Log("No es ping ni solicitud de ubicacion o ruta, entonces no hacemos nada")
		End If
	End If
'	Dim n As Notification
'	n.Initialize
'	n.Icon = "icon"
'	n.SetInfo("Guna", "Guna", Main)
'	n.Notify(1)
End Sub

Sub Service_Destroy

End Sub

Sub SendMessage(params As Map)
	Dim topic As String= params.Get("topic")
	Dim title As String= params.Get("title")
	Dim body As String= params.Get("body")
	Dim tipo As String= params.Get("t")
	If params.ContainsKey("r") Then
		Log("Con ruta")
		Dim rutaGpsCmp As String= params.Get("r")
	Else
		Log("Sin ruta")
		Dim rutaGpsCmp As String = ""
	End If
	Dim Job As HttpJob
	Job.Initialize("fcm", Me)
	Dim m As Map = CreateMap("to": $"/topics/${topic}"$)
	Dim data As Map = CreateMap("title":title, "body":body, "d":B4XPages.MainPage.usuario, "t":tipo, "b":B4XPages.MainPage.batt, "mt":B4XPages.MainPage.montoActual, "r":rutaGpsCmp, "v":B4XPages.MainPage.v)
	m.Put("data", data)
	Dim jg As JSONGenerator
	jg.Initialize(m)
	Job.PostString("https://fcm.googleapis.com/fcm/send", jg.ToString)
	Job.GetRequest.SetContentType("application/json;charset=UTF-8")
	Job.GetRequest.SetHeader("Authorization", "key=" & API_KEY)
	Log(m) 'ignore
End Sub

Sub mandamosLoc(coords As String)
'	Log("Iniciamos mandamosLoc "&coords)
'	Log("locRequest="&locRequest)
	If locRequest="Activa" Then 'Si hay solicitud de ubicacion, entonces la mandamos ...
		Dim params As Map = CreateMap("topic":Sprvsr,"title":"ubicacionRecibida", "body":coords, "t":"u")
		SendMessage(params)
		locRequest="Enviada"
		CallSubDelayed(Tracker,"CreateLocationRequest")
	End If
End Sub

Sub guardaInfoEnArchivo(coords As String) 'ignore  'Escribimos coordenadas y fecha a un archivo de texto
	Log("Guardamos ubicacion en BD")
	Dim latlon() As String = Regex.Split(",", coords)
	B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO RUTA_GPS(FECHA, LAT, LON) VALUES (?,?,?)", Array As Object (latlon(2),latlon(0),latlon(1)))
End Sub

Sub borramosArchivoGPS
	Dim out As OutputStream = File.OpenOutput(File.DirRootExternal, "gps.txt", False)
	Dim s As String = ""
	Dim t() As Byte = s.GetBytes("UTF-8")
	out.WriteBytes(t, 0, t.Length)
	out.Close
End Sub

Sub pe_BatteryChanged (Level As Int, Scale As Int, Plugged As Boolean, Intent As Intent)
	B4XPages.MainPage.batt=Level
End Sub

Sub compress(str As String) As String
	' Compression
	Private su As StringUtils
	Dim compressed() As Byte = GZip.compress(str)
	Log($"CompressedBytesLength: ${compressed.Length}"$)
	Dim base64 As String = su.EncodeBase64(compressed)
	Log($"CompressedBytes converted to base64 Length: ${base64.Length}"$)
	Log($"CompressedBytes converted to base64: ${base64}"$)
	Return base64
End Sub

Sub decompress(base64 As String) As String 'ignore
	' Decompression
	Private su As StringUtils
	Dim decompressedbytes() As Byte = su.DecodeBase64(base64)
	Log($"decompressedbytesLength: ${decompressedbytes.Length}"$)
	Dim bc As ByteConverter
	Dim uncompressed As String = bc.StringFromBytes(decompressedbytes,"UTF8")
	Log($"uncompressedLength: ${uncompressed.Length}"$) ' 6163 Bytes
	Log($"Decompressed String = ${uncompressed}"$)
	Return uncompressed
End Sub

Sub dameRuta As String
	Log("dameRuta")
	Dim c As Cursor
	c = B4XPages.MainPage.skmt.ExecQuery("select LAT, LON from RUTA_GPS order by FECHA desc limit 390")
	c.Position = 0
	Dim ruta2 As String = ""
	If c.RowCount>0 Then
		For i=0 To c.RowCount -1
			c.Position=i
			ruta2=ruta2&CRLF&c.GetString("LAT")&","&c.GetString("LON")
		Next
	End If
	c.Close
	Return compress(ruta2)
End Sub

Sub borraGPSHist
	c = B4XPages.MainPage.skmt.ExecQuery("delete FROM RUTA_GPS")
End Sub