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 skmt As SQL
	Dim s As C_Subs
	Dim ph As Phone
	Public rp As RuntimePermissions
	Public FLP As FusedLocationProvider
'	Private flpStarted As Boolean
	Dim reqManager As DBRequestManager
	Dim DBReqServer As String = "http://keymon.net:1781"
'	Dim DBReqServer As String = "http://11.0.0.107:1781"
'	Dim DBReqServer As String = "http://10.0.0.205:1783"
'	Dim DBReqServer As String = "http://192.168.100.10:1781"
	Dim Timer1 As Timer
	Dim Interval As Int = 10
	Dim ruta As String = File.DirInternal
	'Para los Logs
	Private logs As StringBuilder
	Private logcat As LogCat
	Dim muestraProgreso = 0
	Dim logger As Boolean = False
	Dim MAC_IMPRESORA As String
	Dim marcaCel As String = ph.manufacturer
	Dim tabla As String
	Dim pre_viejo As Float
	Private BTAdmin As BluetoothAdmin
	Public BluetoothState As Boolean
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")
	s.Initialize(Me, "Subs") 'Inicializamos la clase Subs
	skmt = s.inicializaBD(File.DirInternal, "kmt.db")
	BTAdmin.Initialize("admin")
'	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

Private Sub BTAdmin_StateChanged (NewState As Int, OldState As Int)
	If logger Then Log("BT state changed: " & NewState)
	BluetoothState = NewState = BTAdmin.STATE_ON
'	StateChanged
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)
	If s.traeDBReqServerDeBD(skmt) <> "N/A" And s.traeDBReqServerDeBD(skmt) <> "" Then DBReqServer = s.traeDBReqServerDeBD(skmt)
	reqManager.Initialize(Me, DBReqServer)
	Log($"Starter - |${DBReqServer}|"$)
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
	Dim logger As Boolean = False
	If logger Then LogColor("Iniciamos ENVIA_ULTIMA_GPS", Colors.Magenta)
	Dim cmd As DBCommand
'	cmd.Initialize
'	cmd.Name = "select_fechat"
'	B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "fechat")
	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name = "UPDATE_IZCA_ACTUAL2_GPS"
	If B4XPages.MainPage.lat_gps.Length < 15 Then B4XPages.MainPage.lat_gps = B4XPages.MainPage.lat_gps&"0"
	cmd.Parameters = Array As Object(B4XPages.MainPage.montoActual, B4XPages.MainPage.clientestotal, B4XPages.MainPage.clientesventa,B4XPages.MainPage.clientesvisitados,B4XPages.MainPage.lat_gps,B4XPages.MainPage.lon_gps,B4XPages.MainPage.batt,0, 0, 0,B4XPages.MainPage.ALMACEN,B4XPages.MainPage.rutapreventa)
	If 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}, 0, 0, 0, Almacen: ${B4XPages.MainPage.ALMACEN}, Ruta: ${B4XPages.MainPage.rutapreventa}"$)
	reqManager.ExecuteCommand(cmd, "inst_visitas")
	skmt.ExecNonQuery2("Update cat_variables set CAT_VA_VALOR = ?  WHERE CAT_VA_DESCRIPCION = ?" , Array As String(DateTime.Time(DateTime.Now),"HoraIngreso"))
	'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

'Inicializa el reqServer con la dirección dada y lo guarda en CAT_VARIABLES.
Sub reinicializaReqManager(srv As String)
	skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("SERVER"))
	skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("SERVER", srv))
	DBReqServer = srv
	reqManager.Initialize(Me, srv)
	LogColor(srv, Colors.red)
End Sub