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
	Dim skmt As SQL
	Public rp As RuntimePermissions
	Public FLP As FusedLocationProvider
'	Private flpStarted As Boolean
	Dim reqManager As DBRequestManager
	Dim server As String = "http://keymon.net:1782"
'	Dim server As String = "http://10.0.0.205:1782"
	Dim Timer1 As Timer
	Dim Interval As Int = 300
	Dim ruta As String = File.DirInternal
	'Para los Logs
	Private logs As StringBuilder
	Private logcat As LogCat
	Dim logger As Boolean = False
	Dim marcaCel As String = ph.manufacturer
	Private BTAdmin As BluetoothAdmin
	Dim MAC_IMPRESORA As String
	Public BluetoothState As Boolean
	Dim ubicacionActual As Location
	Dim enVenta As Boolean = False
	Dim muestraProgreso = 0 'Parte de la funcionalidad "appUpdater"
	Public newApp As mNewVersion 'Parte de la funcionalidad "appUpdater"
	Dim nuevoLink As String
	Dim idCliente As String = ""
	Dim encuesta As String = 0
	Public fFileProvider As FileProvider
	Dim tabla As String
	Dim enCliente As Boolean = False
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
	BTAdmin.Initialize("admin")
	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
	fFileProvider.Initialize
	CallSubDelayed(FirebaseMessaging, "SubscribeToTopics") 'Para Push FirebaseMessaging
	ubicacionActual.Initialize
	If File.Exists(File.DirInternal, "kmt.db") = False Then
		File.Copy(File.DirAssets, "kmt.db", File.DirInternal, "kmt.db")
	End If
	skmt.Initialize(File.DirInternal,"kmt.db", True)
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)
	Private s As Cursor = skmt.ExecQuery("select * from cat_variables where cat_va_descripcion = 'DBReqServer'")
	If s.RowCount > 0 Then 'Si tenemso valor en BD lo tomamos.
		s.Position = 0
		server = s.GetString("CAT_VA_VALOR")
	Else 'Si no hay valor de BD usamos el defaut.
		skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("DBReqServer"))
		skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("DBReqServer", server))
	End If
	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
	LogColor("Iniciamos ENVIA_ULTIMA_GPS", Colors.Magenta)
	Dim skmt As SQL
	Dim cmd As DBCommand
	skmt.Initialize(ruta,"kmt.db", True)
'	cmd.Initialize
'	cmd.Name = "select_fechat"
'	B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "fechat")
	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name = "UPDATE_GUNA_ACTUAL2_GPS2"
	Private s7 As Cursor = B4XPages.MainPage.skmt.ExecQuery("select SUM(PE_CANT) AS PE_CANT, PE_PROID FROM PEDIDO WHERE PE_PROID IN (SELECT CAT_GP_ID FROM CAT_GUNAPROD WHERE CAT_GP_TIPO = 'CIGARRO') GROUP BY PE_PROID")
	If s7.RowCount > 0 Then
		Dim totalstick As Int = 0
		For sfsdf = 0 To s7.RowCount -1
			s7.Position= sfsdf
			Log("ENTRE AQUI")
			Dim s8 As Cursor = B4XPages.MainPage.skmt.ExecQuery($"SELECT ifnull(CAT_GP_CONVERSION3,0) as CAT_GP_CONVERSION3 FROM CAT_GUNAPROD WHERE CAT_GP_ID = '${s7.GetString("PE_PROID")}'"$)
			s8.Position = 0
			totalstick = totalstick + (s7.GetString("PE_CANT")* s8.GetString("CAT_GP_CONVERSION3"))
			Dim totalpaquete As Int = 0
		
			totalpaquete = totalpaquete +(totalstick/200)
			Log(totalpaquete)
		Next
	End If
	
		
	
	cmd.Parameters = Array As Object(NumberFormat2(B4XPages.MainPage.montoActual,0,2,2,False), B4XPages.MainPage.clientestotal, B4XPages.MainPage.clientesventa,B4XPages.MainPage.clientesvisitados,B4XPages.MainPage.lat_gps,B4XPages.MainPage.lon_gps,B4XPages.MainPage.batt,0, totalpaquete,totalstick,encuesta,B4XPages.MainPage.ALMACEN,B4XPages.MainPage.rutapreventa)
'	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, "actualizaUltimaGPS")
	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

Sub JobDone(Job As HttpJob)
	Log("JOBDONE STARTER")
'	Log(Job.Tag)
	If Job.Success = False Then ' Si hay unerror en el request...
'		Log("JOBDONE ERROR")
		LogColor("Error: " & Job.ErrorMessage, Colors.red)
	Else 'If Job Success then ...
		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = B4XPages.MainPage.reqManager.HandleJob(Job)
			Log($"Tag: ${RESULT.tag}, success=${Job.Success}"$)
		End If
'		Log("JOBDONE SUCCESS")
	End If
End Sub