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

Sub Process_Globals
	'These global variables will be declared once when the application starts.
	'These variables can be accessed from all modules.
	Public gps As GPS
	Dim ph As Phone
	Public rp As RuntimePermissions
	Public FLP As FusedLocationProvider
'	Private flpStarted As Boolean
	Dim reqManager As DBRequestManager
	Dim server As String = "http://187.189.244.154:1781"
'	Dim server As String = "http://187.189.244.154:1783"
'	Dim server As String = "http://10.0.0.205:1782"
'	Dim server As String = "http://11.0.0.231:1782"
	Dim Timer1 As Timer
	Dim Interval As Int = 500
	Dim ruta As String = File.DirInternal
	'Para los Logs
	Private logs As StringBuilder
	Private logcat As LogCat
	Dim dia_semana As String = ""
	Dim logger As Boolean = False
	Dim marcaCel As String = ph.manufacturer
	Public rp As RuntimePermissions
End Sub

Sub Service_Create
	'This is the program entry point.
	'This is a good place to load resources that are not specific to a single activity.
	gps.Initialize("GPS")
'	CallSubDelayed(FirebaseMessaging, "SubscribeToTopics") 'Para Push FirebaseMessaging
	Timer1.Initialize("Timer1", Interval * 1000)
	Timer1.Enabled = True
'	'Para los Logs
	#if RELEASE
	logcat.LogCatStart(Array As String("-v","raw","*:F","B4A:v"), "logcat")
	#end if
	logs.Initialize
'	CallSubDelayed(FirebaseMessaging, "SubscribeToTopics") 'Para Push FirebaseMessaging
End Sub

Sub Service_Start (StartingIntent As Intent)
	Service.StopAutomaticForeground 'Starter service can start in the foreground state in some edge cases.
	Subs.revisaBD
'	Log(marcaCel)
	reqManager.Initialize(Me, server)
End Sub

Private Sub Timer1_Tick
'	Log("Next run " & DateTime.Time(DateTime.Now + Interval * 1000))
	ENVIA_ULTIMA_GPS
End Sub

Sub GPS_LocationChanged (Location1 As Location)
'	CallSub2(Main, "GPS_LocationChanged", Location1)
End Sub

Sub Service_TaskRemoved
	'This event will be raised when the user removes the app from the recent apps list.
End Sub

Sub Service_Destroy

End Sub

Sub ENVIA_ULTIMA_GPS
'	reqManager.Initialize(Me, server)
	Dim logger As Boolean = True
	If logger Then LogColor("Iniciamos ENVIA_ULTIMA_GPS", Colors.Magenta)
	Dim skmt As SQL
	skmt.Initialize(ruta,"kmt.db", False)

	If Subs.traeAlmacen <> Null And Subs.traeAlmacen <> "" Then
		'Primero borramos de CAT_RUTAS_CENSOS el registro (por almacen y ruta)
		'y LUEGO lo insertamos en JobDone
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "deleteRutaCensos2"
		cmd.Parameters = Array As Object(Subs.traeAlmacen, B4XPages.MainPage.principal.l_ruta.text, Subs.traeUsuarioDeBD)
		reqManager.ExecuteCommand(cmd , "delCatRutas")
	End If

	'Reiniciamos el timer para cuando llamamos el Sub desde "seleccion"
	Timer1.Enabled = False
	Timer1.Interval = Interval * 1000
	Timer1.Enabled = True
End Sub

'Para los Logs
Private Sub logcat_LogCatData (Buffer() As Byte, Length As Int)
	logs.Append(BytesToString(Buffer, 0, Length, "utf8"))
	If logs.Length > 4000 Then
		logs.Remove(0, logs.Length - 2000) 'Obtenemos log de 2000 ~ 4000 chars
	End If
End Sub

'Return true to allow the OS default exceptions handler to handle the uncaught exception. 'Para los Logs
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
	'wait for 500ms to allow the logs to be updated.
	Dim jo As JavaObject
	Dim l As Long = 500: jo.InitializeStatic("java.lang.Thread").RunMethod("sleep", Array(l)) 'Sleep 500ms
	logcat.LogCatStop
	logs.Append(StackTrace)
	Subs.revisaBD
	Subs.errorLog.ExecNonQuery2("INSERT INTO errores(fecha, error) VALUES (?,?)", Array As Object (Subs.fechaKMT(DateTime.now), logs))
	Return True
End Sub


Sub JobDone(Job As HttpJob)
'	Log(Job.Success)
	If Job.Success = False Then
'		ToastMessageShow("Error: " & Job.ErrorMessage, True)
		LogColor("Error: " & Job.ErrorMessage, Colors.red)
	Else
		LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green)  'Mod por CHV - 211027
		If Job.JobName = "DBRequest" Then
			Dim resultado As DBResult = reqManager.HandleJob(Job)
			If resultado.Tag = "confirmaCliente" Then
				Subs.logJobDoneResultados(resultado)
			End If
			If resultado.Tag = "ins_UTR" Then
				Subs.logJobDoneResultados(resultado)
			End If
			If resultado.Tag = "delCatRutas" Then
				Subs.logJobDoneResultados(resultado)
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_UTR_MARDS_C"
				If B4XPages.MainPage.lat_gps.Length < 15 Then B4XPages.MainPage.lat_gps = B4XPages.MainPage.lat_gps&"0"
				cmd.Parameters = Array As Object(Subs.traeAlmacen, B4XPages.MainPage.batt, B4XPages.MainPage.principal.l_dia.text, B4XPages.MainPage.principal.l_nuevos_c.text, B4XPages.MainPage.principal.l_nuevos_p.text, B4XPages.MainPage.principal.l_ruta.Text, B4XPages.MainPage.principal.l_total.text, Subs.traeUsuarioDeBD, B4XPages.MainPage.principal.l_visitados.text, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps)
''				If logger Then Log($"${Subs.traeAlmacen}, ${B4XPages.MainPage.batt}, ${B4XPages.MainPage.principal.l_dia.text}, ${B4XPages.MainPage.principal.l_nuevos_c.text}, ${B4XPages.MainPage.principal.l_nuevos_p.text}, ${B4XPages.MainPage.principal.l_ruta.Text}, ${B4XPages.MainPage.principal.l_total.text}, ${Subs.traeUsuarioDeBD}, ${B4XPages.MainPage.principal.l_visitados.text}, ${B4XPages.MainPage.lat_gps}, ${B4XPages.MainPage.lon_gps}"$)
				reqManager.ExecuteCommand(cmd, "ins_UTR")
			End If
		End If
		Job.Release
	End If
	
End Sub
