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 rp As RuntimePermissions
	Public FLP As FusedLocationProvider
	Private flpStarted As Boolean
	Dim skmt As SQL
	Dim ruta As String
	Private BTAdmin As BluetoothAdmin
	Public BluetoothState As Boolean
	Dim Timer1 As Timer
	Dim Interval As Int = 300
	'Para WebSockets
'	Dim monitor As Timer 'Lo usamos para monitorear los servicios Tracker y PushService
'	Dim monitorTicks As Int = 0
	Dim trackerActividad  As String = "501231235959"
	Dim pushServiceActividad As String = "501231235959"
	'Para los Logs
	Dim MAC_IMPRESORA As String
	Private logs As StringBuilder
	Private logcat As LogCat
	Public SharedFolder As String 'Para actualizar apk
	Dim cedisLocation As Location
	Dim reqManager As DBRequestManager
'	Dim server As String = "http://187.189.244.154:1782"
	Dim server As String = "http://keymon.net:1782"
'	Dim server As String = "http://keymon.lat:9000"
'	Dim server = "http://192.168.100.10:1781"
	Dim muestraProgreso = 0
	Dim c As Cursor
	Dim inicioMapa As Boolean = False
	Dim inicioLat As Double = 0
	Dim inicioLon As Double = 0
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.
	ruta = File.DirInternal 'Ruta de la base de datos por defecto.
'	If File.ExternalWritable Then ruta = rp.GetSafeDirDefaultExternal("") 'Si podemos escribir a la tarjeta, cambiamos la ruta.
	If Not(File.Exists(ruta, "kmt.db")) Then File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db") 'Si no existe el archivo de la base de datos, lo copiamos.
	Log(ruta)
	skmt.Initialize(ruta,"kmt.db", True)
'	CallSubDelayed(PushService, "SubscribeToTopics")
'	CallSubDelayed(FirebaseMessaging, "SubscribeToTopics")
'	BTAdmin.Initialize("admin")
'	If BTAdmin.IsEnabled = False Then
'		If BTAdmin.Enable = False Then
'			ToastMessageShow("Error enabling Bluetooth adapter.", True)
'		Else
'			ToastMessageShow("Enabling Bluetooth adapter...", False)
'		End Ifate = True
'	Else
'		BluetoothSt
'	End If
'	reqManager.Initialize(Me, Main.server)
	Timer1.Initialize("Timer1", Interval * 1000)
	Timer1.Enabled = True
	SharedFolder = rp.GetSafeDirDefaultExternal("")
	cedisLocation.Initialize
'	cedisLocation.Latitude = "19.48118148992086"
'	cedisLocation.Longitude = "-99.15295579261536"
	cedisLocation.Latitude = "20.5879843"
	cedisLocation.Longitude = "-100.3897913"
End Sub

Sub Service_Start (StartingIntent As Intent)
	Service.StopAutomaticForeground 'Starter service can start in the foreground state in some edge cases.
'	StartService(PushService)
'	monitor.Initialize("monitor", 30000)
'	monitor.Enabled = True
End Sub

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

'Return true to allow the OS default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
	Return True
End Sub

Sub Service_Destroy

End Sub

Private Sub Timer1_Tick
'	ToastMessageShow("Timer",False)
'	LogColor("Siguiente actualizacion " & DateTime.Time(DateTime.Now + Interval * 1000),Colors.Blue)
	
	ENVIA_ULTIMA_GPS
End Sub

Sub ENVIA_ULTIMA_GPS
	If IsConnectedToInternet Then
		Log("Con internet, enviamos UTR!")
		Dim skmt As SQL
		Dim cmd As DBCommand
		Dim reqManager As DBRequestManager
		reqManager.Initialize(Me, server)
'		LogColor($"ReqServer = ${server}"$, Colors.red)
		skmt.Initialize(ruta,"kmt.db", True)
'		Log("server: "&Main.server)
		skmt.Initialize(ruta,"kmt.db", True)
'		If B4XPages.MainPage.logger Then LogColor("Iniciamos ENVIA_ULTIMA_GPS", Colors.red)
		DateTime.TimeFormat = "HHmmss"
		B4XPages.MainPage.ultimaActualizacionGPS = DateTime.Time(DateTime.Now)
		cmd.Initialize
		cmd.Name = "select_fechat"
		reqManager.ExecuteQuery(cmd , 0, "fechat")

		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "UPDATE_ACTUAL_GPS_GUNA_VN"
'		cmd.Parameters = Array As Object(B4XPages.MainPage.clientesvisitados, B4XPages.MainPage.clientestotal, B4XPages.MainPage.clientesventa, B4XPages.MainPage.montoRechazado, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, B4XPages.MainPage.batt, B4XPages.MainPage.montoEntregado, B4XPages.MainPage.montoRechazado,B4XPages.MainPage.clientestotal, B4XPages.MainPage.porVisitar, B4XPages.MainPage.entregas, B4XPages.MainPage.rechazos, B4XPages.MainPage.ALMACEN, B4XPages.MainPage.rutapreventa )
		cmd.Parameters = Array As String(B4XPages.MainPage.montoActual,B4XPages.MainPage.montoRechazado,B4XPages.MainPage.monto_entregadoactual,B4XPages.MainPage.piezas_entregdas, B4XPages.MainPage.clientestotal,B4XPages.MainPage.entregas, B4XPages.MainPage.rechazos, (B4XPages.MainPage.rechazos + B4XPages.MainPage.entregas), B4XPages.MainPage.porVisitar,  B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, B4XPages.MainPage.batt,Application.VersionName,B4XPages.MainPage.ALMACEN, B4XPages.MainPage.rutapreventa)
'		Log(B4XPages.MainPage.montoActual&"  , "&B4XPages.MainPage.montoRechazado&"  , "&B4XPages.MainPage.monto_entregadoactual&"  , "&B4XPages.MainPage.piezas_entregdas&"  , "&B4XPages.MainPage.clientestotal&"  , "&B4XPages.MainPage.entregas&"  , "&B4XPages.MainPage.rechazos&"  , "&(B4XPages.MainPage.rechazos + B4XPages.MainPage.entregas)&"  , "&B4XPages.MainPage.porVisitar)
'		Log(B4XPages.MainPage.montoActual&",  "&B4XPages.MainPage.montoRechazado&",  "&B4XPages.MainPage.monto_entregadoactual&",  "&B4XPages.MainPage.piezas_entregdas&",  "& B4XPages.MainPage.clientestotal&",  "&B4XPages.MainPage.entregas&",  "& B4XPages.MainPage.rechazos&",  "& (B4XPages.MainPage.rechazos + B4XPages.MainPage.entregas)&",  "& B4XPages.MainPage.porVisitar&",  "&  B4XPages.MainPage.lat_gps&",  "& B4XPages.MainPage.lon_gps&",  "& B4XPages.MainPage.batt&",  "&Application.VersionName&",  "&B4XPages.MainPage.ALMACEN&",  "& B4XPages.MainPage.rutapreventa)
'		If B4XPages.MainPage.logger Then Log($"montoActual: ${B4XPages.MainPage.montoActual}, cTotal: ${B4XPages.MainPage.clientestotal}, cVenta: ${B4XPages.MainPage.clientesventa}, cVisitados: ${B4XPages.MainPage.clientesvisitados}, ${B4XPages.MainPage.lat_gps}, ${B4XPages.MainPage.lon_gps}, Batt: ${B4XPages.MainPage.batt}, montoRechazado: ${B4XPages.MainPage.montoRechazado}, montoEntregado: ${B4XPages.MainPage.montoEntregado}, porVisitar: ${B4XPages.MainPage.porVisitar}, entregas: ${B4XPages.MainPage.entregas}, rechazos: ${B4XPages.MainPage.rechazos}, Almacen: ${B4XPages.MainPage.ALMACEN}, Ruta: ${B4XPages.MainPage.rutapreventa}"$)
		reqManager.ExecuteCommand(cmd, "up_geolocalizacion")
		skmt.ExecNonQuery2("Update cat_variables set CAT_VA_VALOR = ?  WHERE CAT_VA_DESCRIPCION = ?" , Array As String(DateTime.Time(DateTime.Now),"HoraIngreso"))

		If B4XPages.MainPage.principal.IsInitialized Then
			B4XPages.MainPage.principal.envia_reparto
		End If

		'Reiniciamos el timer para cuando llamamos el Sub desde otra actividad
		Timer1.Enabled = False
		Timer1.Interval = Interval * 1000
		Timer1.Enabled = True
	Else
		Log("Sin conexión a internet, no se envió UTR!")
	End If
End Sub






Sub IsConnectedToInternet As Boolean 'ignore
	Dim r As Reflector
	r.Target = r.GetContext
	r.Target = r.RunMethod2("getSystemService", "connectivity", "java.lang.String")
	r.Target = r.RunMethod("getActiveNetworkInfo")
	If r.Target <> Null Then
		Return r.RunMethod("isConnectedOrConnecting")
	End If
	Return False
End Sub

Sub JobDone(Job As HttpJob)
'	LogColor("starter jobdone", Colors.Red)
'	Log(Job.ErrorMessage)
'	Private r As DBResult = reqManager.HandleJob(Job)
	If Job.Success = False Then
'		LogColor("** " & Job.Tag & " Error: " & Job.ErrorMessage, Colors.Red) ' Mod by CHV - 211023
		If Job.ErrorMessage.Contains("failed to connect") Or Job.ErrorMessage.Contains("Failed to connect") Then
			ToastMessageShow("!Hubo un error contactando al servidor, por favor revise su conexión!", True)
		End If
		'ToastMessageShow("Error: " & Job.ErrorMessage, True)
	Else
'		LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green)  'Mod por CHV - 211023
	End If
End Sub