B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=9.85
@EndOfDesignText@
#Region Shared Files
'#CustomBuildAction: folders ready, %WINDIR%\System32\Robocopy.exe,"..\..\Shared Files" "..\Files"
	'Ctrl + click to sync files: ide://run?file=%WINDIR%\System32\Robocopy.exe&args=..\..\Shared+Files&args=..\Files&FilesSync=True
	'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip
	'###########################################################################################################
	'######################           PULL         #############################################################
	'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=git&Args=pull
	'###########################################################################################################
	'######################        PULL FORZADO    #############################################################
	'Ctrl + click Respaldar y Pull: ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=start&Args=powershell.exe&Args=-ExecutionPolicy&Args=Bypass&Args=-File&Args=..\..\_sync_project.ps1
	'###########################################################################################################
	'######################           PUSH         #############################################################
	'Ctrl + click ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=github&Args=..\..\
	'###########################################################################################################
	'######################      PUSH TORTOISE GIT     #########################################################
	'Ctrl + click ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=TortoiseGitProc&Args=/command:commit&Args=/path:"./../../"&Args=/closeonend:2
	'###########################################################################################################
	'######################      PUSH TORTOISE GIT CON TAG    ##################################################
	'Ctrl + clic para Git: ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=-ExecutionPolicy&Args=Bypass&Args=-File&Args=..\_git_tag.ps1&Args=%22%PROJECT%%22&Args=%22%PROJECT_NAME%%22
	'###########################################################################################################
#End Region

'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=github&Args=..\..\

Sub Class_Globals
	Private Root As B4XView
	Private xui As XUI
	Dim s As C_Subs
	Public login As B4XMainPage
	Public principal As C_Principal
	Public clientes As C_Clientes
	Public cliente As C_Cliente
	Public productos As C_Productos
	Public updateAvailable As C_UpdateAvailable
	Public mapas As C_Mapas
	Public nuevoCliente As C_NuevoCliente
	Public ticketsDia As C_TicketsDia
	Public noVenta As C_NoVenta
	Public nota As C_Nota
	Public pedidos As C_Pedidos
	Public promos As C_Promos
	Public historico As C_Historico
	Public Provider As FileProvider
 
	'nuevocliente -> NuevoCliente
	'buscar -> ticketsDia
	'colonia -> clientes
	'nopago -> noVenta
	'tarjeta -> Nota
	'fila -> Cliente
	'colonia2 -> Productos
	
	'xxxxxxxxxxxxxxxxxxxxxxxxx

	Dim reqManager As DBRequestManager
	Dim v As String = Application.VersionName
	Dim ruta As String
	Dim tgl As Toggle
	Dim lat_gps, lon_gps As String
	Dim usuario As String
	Dim batt As Int
	Dim skmt As SQL
	Dim montoActual, clientesTotal, clientesVenta, clientesVisitados,almacen, rutaPreventa As String
	Dim DBReqServer, fechaRuta As String
	Dim Logger As Boolean
	Dim mac_impresora As String
	Dim Phn As PhoneId
	
	Dim user As EditText
	Dim pass As EditText
	Dim c As Cursor
	Dim existe As String
	Dim paso1 As String
	Private IMEN As Label
	Dim IMEI As String = ""
	Dim alterno As String
	Private b_menu As Button
	Dim PopupMenu As RSPopupMenu
	Dim cmd As DBCommand
	Private PDF As Button
	Private bpv1 As BatteryProgressView
	Dim batterystatus(11) As Int
	Private bu As BatteryUtilities
	Private b_apk As Button
	Private i_engrane As ImageView
	Private p_Main As Panel
	Private p_appUpdate As Panel
	Private b_regesar As Button
	Private l_version As Label
	Private ImageView1 As ImageView
	Private Label2 As Label
	Private Entrar As Button
	Dim tipo_venta As String
	Dim bTerminarClicked As Boolean = False
	Private lv_server As ListView
	Private l_server As Label
	Private b_enviarbd As Button
	Private b_importarBD As Button
	Dim ime As IME
	Dim MES1 As ManageExternalStorage
	Dim device As Phone
	Private et_server As EditText
	Private b_guardar As Button
End Sub

Public Sub Initialize
'	B4XPages.GetManager.LogEvents = True
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
	B4XPages.GetManager.LogEvents = True
	Root = Root1
	Root.LoadLayout("login")
	s.Initialize(Me, "Subs")
	B4XPages.SetTitle(Me, "Intmex Preventa")
	login.Initialize
	B4XPages.AddPage("Login", login)
	principal.Initialize
	B4XPages.AddPage("Principal", principal)
	clientes.Initialize
	B4XPages.AddPage("Clientes", clientes)
	cliente.Initialize
	B4XPages.AddPage("Cliente", cliente)
	productos.Initialize
	B4XPages.AddPage("Productos", productos)
	updateAvailable.Initialize
	B4XPages.AddPage("updateAvailable", updateAvailable)
	mapas.Initialize
	B4XPages.AddPage("Mapas", mapas)
	nuevoCliente.Initialize
	B4XPages.AddPage("NuevoCliente", nuevoCliente)
	ticketsDia.Initialize
	B4XPages.AddPage("TicketsDia", ticketsDia)
	noVenta.Initialize
	B4XPages.AddPage("NoVenta", noVenta)
	nota.Initialize
	B4XPages.AddPage("Nota", nota)
	pedidos.Initialize
	B4XPages.AddPage("Pedidos", pedidos)
	promos.Initialize
	B4XPages.AddPage("Promos", promos)
	historico.Initialize
	B4XPages.AddPage("Historico", historico)
'	respaldoDiario.Initialize
'	B4XPages.AddPageAndCreate("respaldoDiario", respaldoDiario)
	ruta = Starter.ruta
	Provider.Initialize
'	Subs.borraArribaDe100Errores 	' Para Websockets
'	Subs.borraArribaDe600RenglonesBitacora 	' Para Websockets
	If File.Exists(ruta, "kmt.db") = False Then
		File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db")
		LogColor("copiamos kmt.db de "&File.DirAssets & " a " & ruta,Colors.Green)
	End If
	
'	Log(ruta)
	skmt.Initialize(ruta,"kmt.db", True)
	Subs.guardaAppInfo(skmt)
	
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_GIRO(GIRO TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CN(ACTIVO TEXT)")
	
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CLIENTES_NUEVOS(CN_ID TEXT, CN_FECHA TEXT, CN_USER TEXT, CN_LAT TEXT, CN_LON TEXT, CN_NOMBRE TEXT, CN_DIRECCION TEXT, CN_FOTO TEXT, CN_ALMACEN TEXT, CN_RUTA TEXT,CN_GIRO TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_CUOTAS (HC_META6 TEXT, HC_META5 TEXT, HC_META4 TEXT, HC_META3 TEXT, HC_META2 TEXT, HC_META1 TEXT, HC_RUTA TEXT, HC_CUOTA1 TEXT, HC_CUOTA2 TEXT, HC_CUOTA3 TEXT, HC_CUOTA4 TEXT, HC_CUOTA5 TEXT, HC_CUOTA6 TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_GPS (HGDATE TEXT, HGLAT TEXT, HGLON TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_GUNAPROD2 (CAT_GP_INICIATIVA TEXT, CAT_GP_TIPOPROD TEXT, CAT_GP_DEV TEXT, CAT_GP_ALMACEN NUMERIC, CAT_GP_ID TEXT, CAT_GP_NOMBRE TEXT, CAT_GP_IMP1 TEXT, CAT_GP_IMP2 TEXT, CAT_GP_PRECIO TEXT, CAT_GP_CLASIF TEXT, CAT_GP_STS TEXT, CAT_GP_TIPO TEXT, CAT_GP_SUBTIPO TEXT, CAT_GP_IMG BLOB)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_STAY_STORE (HSS_CODIGO TEXT, HSS_IN TEXT, HSS_OUT TEXT, HSS_TOT TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_STAY_OUT (HSO_INI TEXT, HSO_FIN TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS TELEFONO(TEL TEXT, CLIENTE TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS INVENT_X_ENVIAR (ALMACEN TEXT, PROID TEXT, CANTIDAD TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_RESUM_APK (HIST_RA_OBJMES TEXT, HIST_RA_VENTA TEXT, HIST_RA_TENDENCIA TEXT, HIST_RA_ALCANCE TEXT, HISR_RA_DRAOBJ TEXT, HIST_RA_DRAVTA TEXT, HIST_RA_DSOBJ TEXT, HIST_RA_DSVTA TEXT, HIST_RA_VPOOBJ TEXT, HIST_RA_VPOVTA TEXT, HIST_RA_COBCCC TEXT, HIST_RA_CTES TEXT, HIST_RA_ECO TEXT, HIST_RA_VISITPLAN TEXT, HIST_RA_VISIREAL TEXT, HIST_RA_COBVISIT TEXT, HIST_RA_FRECCOMPOBJ TEXT, HIST_RA_FRECCOMREAL TEXT, HIST_RA_VENTAMES1 TEXT, HIST_RA_VENTAMES2 TEXT, HIST_RA_VENTAMES3 TEXT, HIST_RA_VENTAMES4 TEXT, HIST_RA_RECHAZO TEXT, HIST_RA_RECHAZOPORCEN TEXT, HIST_RA_SEMANA1 TEXT, HIST_RA_SEMANA1_DIAS TEXT, HIST_RA_SEMANA1_DRA TEXT, HIST_RA_SEMANA2 TEXT, HIST_RA_SEMANA2_DIAS TEXT, HIST_RA_SEMANA2_DRA TEXT, HIST_RA_SEMANA3 TEXT, HIST_RA_SEMANA3_DIAS TEXT, HIST_RA_SEMANA4 TEXT, HIST_RA_SEMANA3_DRA TEXT, HIST_RA_SEMANA4_DIAS TEXT, HIST_RA_SEMANA4_DRA TEXT, HIST_RA_SEMANA5 TEXT, HIST_RA_SEMANA5_DIAS TEXT, HIST_RA_SEMANA5_DRA TEXT, HIST_RA_SEMANA1_LPT TEXT, HIST_RA_SEMANA2_LPT TEXT, HIST_RA_SEMANA3_LPT TEXT, HIST_RA_SEMANA4_LPT TEXT, HIST_RA_SEMANA5_LPT TEXT, HIST_RA_RUTA TEXT, HIST_RA_IDALMACEN TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_COMISIONES_MOVIL (HCM_IDALMACEN TEXT, HCM_RUTA TEXT, HCM_TOTAL_V TEXT, HCM_TOTAL_VIVE TEXT, HCM_TOTAL_GUNA TEXT,	HCM_TOTAL_BEB TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_GEOCERCA (HGCLIENTE TEXT, HGDATE TEXT, HGLAT TEXT, HGLON TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_FACE (HFCLIENTE TEXT, HFALIAS TEXT, HFRUTA TEXT, HFALMACEN TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS RUTA_GPS(FECHA INTEGER, LAT TEXT, LON TEXT)")
	skmt.ExecNonQuery("CREATE VIEW IF NOT EXISTS CATALOGO AS Select CAT_GP_CLASIF, CAT_GP_ID FROM CAT_GUNAPROD UNION Select CAT_GP_CLASIF, CAT_GP_ID FROM CAT_GUNAPROD GROUP BY CAT_GP_CLASIF, CAT_GP_ID")
	skmt.ExecNonQuery("CREATE VIEW IF NOT EXISTS total_marcas AS 	Select  cat_gp_clasif, sum(pe_costo_tot) As total from CATALOGO, pedido where pe_proid = cat_gp_id 	And pe_cliente <> 0 	group by cat_gp_clasif")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_MARCAS_CUOTAS ( HMC_MARCA TEXT, HMC_TOTAL TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_CODIGO_BARRAS(CODIGOKMTS TEXT, CODIGOB TEXT, LAT TEXT, LON TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS ABONOS (a_usuario TEXT, a_ruta TEXT, a_cliente TEXT, a_abono TEXT, a_fecha TEXT, a_enviado TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS COORDENADAS_GPS (tienda_id TEXT, ruta TEXT, almacen TEXT, latitud TEXT, longitud TEXT, fecha TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_CUESTIONARIO (HC_CLIENTE TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS NOVENTA (NV_CLIENTE TEXT, NV_FECHA TEXT, NV_USER TEXT, NV_MOTIVO TEXT, NV_COMM TEXT, NV_LAT TEXT, NV_LON TEXT)")
	Subs.agregaColumna("PEDIDO", "PE_ENVIO_OK", "INT")
	Subs.agregaColumna("NOVENTA", "NV_ENVIO_OK", "INT")
	Subs.agregaColumna("PEDIDO", "PE_TICKET", "INT")
	Subs.agregaColumna("CLIENTES_NUEVOS", "CN_COLONIA", "TEXT")
	Subs.agregaColumna("CLIENTES_NUEVOS", "CN_TELEFONO", "TEXT")
	Subs.agregaColumna("CLIENTES_NUEVOS", "CN_CP", "TEXT")
	Subs.agregaColumna("CLIENTES_NUEVOS", "CN_SOLICITA", "TEXT")
	Subs.agregaColumna("CLIENTES_NUEVOS", "CN_ENVIO", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD2", "CAT_GP_PRECIO8", "TEXT DEFAULT '0'")
	Subs.agregaColumna("CAT_GUNAPROD2", "CAT_GP_PRECIO9", "TEXT DEFAULT '0'")
	Subs.agregaColumna("CAT_GUNAPROD2", "CAT_GP_PRECIO10", "TEXT DEFAULT '0'")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRECIO8", "TEXT DEFAULT '0'")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRECIO9", "TEXT DEFAULT '0'")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRECIO10", "TEXT DEFAULT '0'")
	Subs.agregaColumna("PEDIDO_CLIENTE", "PC_GUARDADO", "TEXT DEFAULT '0'")
	Subs.agregaColumna("CAT_GUNAPROD2", "CAT_GP_VARREQ3", "TEXT DEFAULT '0'")
	
	Subs.agregaColumna("CAT_GUNAPROD2", "MARCA", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "MARCA", "TEXT")

	c=skmt.ExecQuery("select  COUNT(*) AS CUANTOS from HIST_STAY_OUT ")
	C.Position = 0
	If c.GetString("CUANTOS")  = 0 Then
		skmt.ExecNonQuery("INSERT INTO HIST_STAY_OUT(HSO_INI, HSO_FIN) VALUES (0,0)")
	End If
	C.Close
'	server = "http://keymon.com.mx:1782"
	'server = "http://201.99.139.28:1783"
'	reqManager.Initialize(Me, DBReqServer)
	l_version.Text = Application.VersionName
	'este codigo es para lo del menu
'	PopupMenu.Initialize("PopupMenu", b_menu)
'	PopupMenu.AddMenuItem(0, 0, "View")
'	PopupMenu.AddMenuItem(1, 1, "Edit")
'	PopupMenu.AddMenuItem(2, 2, "Details")
'	PopupMenu.AddMenuItem(3, 3, "Remove")
	' menu fin
	montoActual  = 0
	clientesTotal = 0
	clientesVenta =  0
	clientesVisitados = 0
	almacen = 0
	rutaPreventa =  0
	p_appUpdate.Visible = False
	
	LogColor("Revisa permisos Phone_State", Colors.Green)
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		Log("Con permisos de ubicacion")
	Else
		Log("SIN permisos de ubicacion")
	End If
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_COARSE_LOCATION)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		Log("Con permisos de ubicacion")
	Else
		Log("SIN permisos de ubicacion")
	End If
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_READ_PHONE_STATE)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
'		IMEN.Text = Phn.GetDeviceId
'		IMEI = Phn.GetDeviceId
'		LogColor($"//////////////////  IMEI: ${IMEI} ////////////////// "$, Colors.Blue)
'		IMEI=""  'Pruebas
	End If
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
'	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then
'		StartService(Tracker)
''		Log("Start Tracker")
'	Else
'		ToastMessageShow("No permission", True)
'	End If
	MES1.Initialize(Me, "MES1")
	' get the device SDK version
	Dim SdkVersion As Int = device.SdkVersion
	' Choose which permission to request in order to access external storgage
	If SdkVersion < 30 Then
'		Log("SDK = " & SdkVersion & " : Requesting WRITE_EXTERNAL_STORAGE permission")
		Dim rp As RuntimePermissions
		rp.CheckAndRequest(rp.PERMISSION_WRITE_EXTERNAL_STORAGE) ' Implicit read capability if granted
		Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
'		Log($"PERMISSION_WRITE_EXTERNAL_STORAGE = ${Result}"$)
	Else
'		Log("SDK = " & SdkVersion & " : Requesting MANAGE_EXTERNAL_STORAGE permission")
'		Log("On Entry MANAGE_EXTERNAL_STORAGE = " & MES1.HasPermission)
		If Not(MES1.HasPermission) Then
			MsgboxAsync("This app requires access to all files, please enable the option", "Manage All Files")
			Wait For Msgbox_Result(Res As Int)
'			Log("Getting permission")
			MES1.GetPermission
			Wait For MES_StorageAvailable
		End If
	End If
End Sub

Sub B4XPage_Appear
	If Starter.muestraProgreso = 1 Then
		muestraProgreso("Descargando actualización")
		Starter.muestraProgreso = 0
	End If
	Dim ph As Phone 'Get Id Device
	Dim DeviceID As String = ph.GetSettings("android_id").ToUpperCase
	LogColor($"//////////////////   DeviceID: ${DeviceID} ////////////////// "$, Colors.Blue)
	DBReqServer = Starter.DBReqServer
	reqManager.Initialize(Me, Starter.DBReqServer)
	Log("|"&Starter.DBReqServer&"|")
	tgl.Initialize()
	If Not(Starter.gps.GPSEnabled) Then
		ToastMessageShow("Es necesario tener el GPS encendido", True)
		Sleep(500)
		StartActivity(Starter.gps.LocationSettingsIntent)
	End If
	c=skmt.ExecQuery2("select count(*) as CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("FECHA"))
	c.Position = 0
	If c.GetString("CUANTOS") = 0 Then
		LogColor($"No hay fecha: ${c.GetString("CUANTOS")}"$, Colors.Red)
		cmd.Initialize
		cmd.Name = "select_fecha"
		reqManager.ExecuteQuery(cmd , 0, "fecha")
		Msgbox("AJUSTAR FECHA","AVISO") 'Ignore
		B4XPage_Appear
	Else
'		LogColor($"Si hay fecha: ${c.GetString("CUANTOS")}"$, Colors.Green)
		c=skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("FECHA"))
		c.Position =0
		Dim sDate, sTime As String
		DateTime.DateFormat = "yyyyMMdd"
		sDate=DateTime.Date(DateTime.Now)
'		If sDate > "20220701" Then
'			Msgbox("INSTALAR NUEVO APK" ,"AVISO") 'Ignore
'			B4XPage_Appear
'		End If
		If c.GetString("CAT_VA_VALOR") > sDate Then
			Msgbox("AJUSTAR LA FECHA YA QUE ES MENOR AL SISTEMA" ,"AVISO") 'Ignore
			B4XPage_Appear
		End If
	End If
	bu.Initialize
	batterystatus = bu.BatteryInformation
	'Obtenemos el usuario registrado
'	CallSubDelayed(FirebaseMessaging, "SubscribeToTopics")
	dameUsuario
'	If Not(s.CheckNotificationAccess) Then
'		Msgbox2Async($"Se necesita acceso a las notificaciones, haga clic en "Aceptar" y en la siguiente pantalla permita el acceso a la aplicación "${Application.LabelName}"."$, "Permisos necesarios", "Aceptar", "Cancelar", "", Null, True)
'		Wait For Msgbox_Result (resultado As Int)
'		If resultado = DialogResponse.POSITIVE Then
'			Dim In As Intent
'			In.Initialize("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS", "")
'			StartActivity(In)
'		End If
''		Private cd1 As ColorDrawable
''		cd1.Initialize(Colors.red, 10dip)
''		b_notifAccess.Background = cd1
''		b_notifAccess.TextColor = Colors.White
''		b_notifAccess.Text = "Activar Permisos"
'	Else
''		Private cd1 As ColorDrawable
''		cd1.Initialize(Colors.RGB(109, 221, 101), 10dip)
''		b_notifAccess.Background = cd1
''		b_notifAccess.TextColor = Colors.White
''		b_notifAccess.Text = "Permisos Activos"
'	End If
End Sub
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.

Sub Entrar_Click
	Log("|" & Starter.DBReqServer)
	Dim r As Reflector
	Dim Api As Int
	Dim PP As Phone
	Api = r.GetStaticField("android.os.Build$VERSION", "SDK_INT")
	If Api < 9 Then
		'Old device
		If File.Exists(File.DirInternal, "__id") Then
			IMEI =  File.ReadString(File.DirInternal, "__id")
			Log(1&"-"&IMEI)
		Else
			Dim id As Int
			id = Rnd(0x10000000, 0x7FFFFFFF)
			File.WriteString(File.DirInternal, "__id", id)
			IMEI =  id
			Log(2&"-"&IMEI)
		End If
	Else
		'New device
		IMEI =  r.GetStaticField("android.os.Build", "SERIAL")
'		Log(3&"-"&IMEI)
	End If
	If IMEI.ToLowerCase = "unknown" Then
		IMEI = PP.GetSettings("android_id")
	End If
'	Log("IMEI = " &  IMEI)

	If user.Text = "ALTERNO" Then
		c=skmt.ExecQuery2("select CAT_CO_CONFIGURACION, CAT_CO_RESULTADO from CAT_CODIGOS where CAT_CO_PONDERACION =1 AND CAT_CO_ACCION = ?", Array As String("SERVER"))
		c.Position =0
		DBReqServer = c.GetString("CAT_CO_CONFIGURACION")
		alterno = c.GetString("CAT_CO_RESULTADO")
		c.Close
		If alterno = 1 Then
			skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 1 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 2", Array As String ("SERVER"))
			skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 0 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 1", Array As String ("SERVER"))
		Else if alterno = 2 Then
			skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 1 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 1", Array As String ("SERVER"))
			skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 0 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 2", Array As String ("SERVER"))
		End If
		c=skmt.ExecQuery2("select CAT_CO_CONFIGURACION, CAT_CO_RESULTADO from CAT_CODIGOS where CAT_CO_PONDERACION =1 AND CAT_CO_ACCION = ?", Array As String("SERVER"))
		c.Position =0
		DBReqServer = c.GetString("CAT_CO_CONFIGURACION")
		user.Text = DBReqServer
		c.Close
'		reqManager.Initialize(Me, DBReqServer)
	else if user.Text = "KMTS1" Then
		skmt.ExecNonQuery("delete from usuarioa")
		skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object(user.Text, pass.Text))
		skmt.ExecNonQuery("delete from cat_almacen")
		skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (pass.Text))
		skmt.ExecNonQuery("delete from VERSION")
		skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object ("2.1"))
		B4XPages.ShowPage("Clientes")
	else if user.Text = "BERNA1" Then
		skmt.ExecNonQuery("delete from usuarioa")
		skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object(user.Text, "1"))
		skmt.ExecNonQuery("delete from cat_almacen")
		skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object ("1"))
		skmt.ExecNonQuery("delete from VERSION")
		skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object ("2.1"))
		B4XPages.ShowPage("Clientes")
	else if user.Text = "IMEI" Then
		user.Text = IMEI
	End If

	c=skmt.ExecQuery2("select count(*) as EXISTE1 from usuarioa where usuario = ?", Array As String(user.Text))
	c.Position=0
	existe = c.GetString("EXISTE1")
	If existe = 0 Then
		If IMEI = "" Then
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "select_usuario_INTMEX_10" 'Antes select_usuario_guna_GV2_1
			cmd.Parameters = Array As Object(user.Text.Trim, pass.Text.Trim)
			reqManager.ExecuteQuery(cmd , 0, "usuario_10") 'Antes usuario
		Else
			If IMEI = "" Then
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "select_usuario_INTMEX_10"
				cmd.Parameters = Array As Object(user.Text.Trim, pass.Text.Trim)
				reqManager.ExecuteQuery(cmd , 0, "usuario_10")
			Else
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "select_usuario_INTMEX_10" 'Antes select_usuario_guna_GV2
				cmd.Parameters = Array As Object(user.Text.Trim, pass.Text.trim)
				Log("Mandamos: "&user.Text&"|"& pass.Text)
				reqManager.ExecuteQuery(cmd , 0, "usuario_10") 'Antes usuario
			End If
		End If
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "select_version_INTMEX"
		reqManager.ExecuteQuery(cmd , 0, "version")
	Else
		usuario = user.Text
		B4XPages.ShowPage("Principal")
	End If
End Sub

Sub JobDone(Job As HttpJob)
	Log("JOBDONE MAINPAGE")
	If B4XPages.MainPage.reqManager.reqsList.IsInitialized Then 'Si tenemos lista de requests, la procesamos.
		If B4XPages.MainPage.reqManager.reqsList.IndexOf(Job.tag) <> -1 Then
			B4XPages.MainPage.reqManager.reqsList.RemoveAt(B4XPages.MainPage.reqManager.reqsList.IndexOf(Job.tag))
			LogColor($">>>>>> Quitamos ${Job.tag}"$, Colors.Blue)
		End If
		LogColor(">>>>>> " & B4XPages.MainPage.reqManager.reqsList.Size & " - " & B4XPages.MainPage.reqManager.reqsList, Colors.Blue)
	End If
	If Job.Success = False Then
		LogColor("Error: " & Job.tag & " : " & Job.ErrorMessage, Colors.red)
		If Job.Tag = "ping" Then 'query tag
'			Log("ERROR DE PING")
'			B4XPages.MainPage.principal.p_conexion.Color = Colors.red
			If B4XPages.MainPage.principal.l_conexion.IsInitialized Then
				Starter.senial = 0
				B4XPages.MainPage.principal.l_conexion.TextColor = Colors.red
			End If
		End If
	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 result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "ping" Then 'query tag
'				Log("PING OK!!")
				If B4XPages.MainPage.principal.l_conexion.IsInitialized Then
					Starter.senial = 1
					B4XPages.MainPage.principal.l_conexion.TextColor = Colors.Green
				End If
			End If

			If result.Tag = "fecha" Then 'query tag
				For Each records() As Object In result.Rows
					For Each k As String In result.Columns.Keys
						Log("select_fechat: " & k & ": " & records(result.Columns.Get(k)))
					Next
				Next
			End If

			If result.Tag = "version" Then 'query tag
				For Each records() As Object In result.Rows
					skmt.ExecNonQuery("delete from VERSION")
					Dim CAT_VE_VERSION As String = records(result.Columns.Get("CAT_VE_VERSION"))
					skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object (CAT_VE_VERSION))
				Next
			End If

			If result.Tag = "select_fechat" Then 'query tag
				For Each records() As Object In result.Rows
					For Each k As String In result.Columns.Keys
						Log("select_fechat: " & k & ": " & records(result.Columns.Get(k)))
					Next
				Next
			End If

			If result.Tag = "agencia" Then 'query tag
				For Each records() As Object In result.Rows
					Dim ID_ALMACEN As String = records(result.Columns.Get("ID_ALMACEN"))
				Next
			End If

			If result.Tag = "fecha" Then 'query tag
				For Each records() As Object In result.Rows
					Dim FECHA_HOY As String = records(result.Columns.Get("FECHA"))
					skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FECHA"))
					skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FECHA",FECHA_HOY))
				Next
			End If

			If result.Tag = "usuario" Then 'query tag
				For Each records() As Object In result.Rows
					Dim name As String = records(result.Columns.Get("USUARIO"))
					Dim ID_ALMACEN As String = records(result.Columns.Get("CAT_LO_AGENCIA"))
					Dim IMEI_BASE As String = records(result.Columns.Get("CAT_LO_IDTELEFONO"))
					Log(records(result.Columns.Get("CAT_LO_IDTELEFONO")) )
				Next
				paso1 = 1
				ToastMessageShow(name, False)
				Log("//////////////////////////  "&name)
			End If

			If result.Tag = "usuario_10" Then 'query tag
				For Each records() As Object In result.Rows
					Dim name As String = records(result.Columns.Get("USUARIO"))
					Dim ID_ALMACEN As String = records(result.Columns.Get("CAT_LO_AGENCIA"))
					Dim IMEI_BASE As String = records(result.Columns.Get("CAT_LO_IDTELEFONO"))
				Next
				Log("|"&name&"|")
				paso1 = 1
				IMEI_BASE = ""
				IMEI = ""
			End If

			If result.Tag = "ruta" Then 'query tag
				Log("JOBDONE PRINCIPAL MAINPAGE")
				For Each records() As Object In result.Rows
					Dim VALIDO As String = records(result.Columns.Get("VALIDO"))
					If VALIDO = "OK" Then
						Log(VALIDO)
					End If
				Next
			End If
		End If

		Job.Release
	End If
	Log($"Paso1 = ${paso1} - Name: ${name} - IMEI: ${IMEI} - IMEI_BASE: ${IMEI_BASE}"$)
	If paso1 = 1 Then
		If IMEI = "" Then
			If user.Text = "KMTS1" Then name = "OKActivo"
			If name = "OKActivo"  Then
				skmt.ExecNonQuery("delete from usuarioa")
				skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object(user.Text.Trim, pass.Text.Trim))
				skmt.ExecNonQuery("delete from cat_almacen")
				skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (ID_ALMACEN))
				usuario = user.Text
				B4XPages.ShowPage("Principal")
			Else If name  = "OKExpirado" Then
				Msgbox("Usuario Expirado llamar al administrador","") 'Ignore
			Else If name = "OKCancelado" Then
				Msgbox("Usuario Cancelado llamar al administrador","") 'Ignore
			Else
				Msgbox("Usuario o password No validos","") 'Ignore
			End If
			paso1 = 0
		Else
			If name = "OKActivo" & IMEI And  IMEI = IMEI_BASE Then
				If name = "OKActivo" & IMEI Then
					skmt.ExecNonQuery("delete from usuarioa")
					skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object(user.Text.Trim, pass.Text.Trim))
					skmt.ExecNonQuery("delete from cat_almacen")
					skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (ID_ALMACEN))
					usuario = user.Text
					B4XPages.ShowPage("Clientes")
				Else If name  = "OKExpirado"& IMEI Then
					Msgbox("Usuario Expirado llamar al administrador","") 'ignore
				Else If name = "OKCancelado"& IMEI Then
					Msgbox("Usuario Cancelado llamar al administrador","") 'ignore
				Else
					Msgbox("Usuario o password No validos","") 'ignore
				End If
				paso1 = 0
			Else IF  name = "OKActivo" Then
				Msgbox("Telefono no VALIDO!","") 'ignore
			Else
				Msgbox("Usuario o password No validos","") 'ignore
			End If
		End If
	End If
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
	Log("closreq")
	Sleep(0)
	If p_appUpdate.IsInitialized And p_appUpdate.Visible Then
		p_appUpdate.Visible = False
		Return False
	End If
	If Not(p_appUpdate.Visible) Then
		Log("ExitApplication")
		ExitApplication
	End If
	Return True
End Sub

Sub GPS_LocationChanged (Location1 As Location)
	If user.text = "GPS" Then
		user.Text=Location1.Latitude
		pass.text=Location1.Longitude
	End If
End Sub

Sub PopupMenu_Dismiss
	ToastMessageShow("PopupMenu dismissed", False)
End Sub

Sub PopupMenu_MenuItemClick (ItemId As Int) As Boolean
	ToastMessageShow("Item " & ItemId & " clicked.", False)
	Return False
End Sub

Sub b_menu_Click
	PopupMenu.Show
End Sub

Sub PDF_Click

End Sub

'Private Sub GetAdvertisingId As ResumableSub
'	Dim jo As JavaObject = Me
'	jo.RunMethod("GetAdvertisingId", Null)
'	Wait For AdvertisingId_Ready (Success As Boolean, Id As String)
'	Return Id
'End Sub

Sub dameUsuario
	c=skmt.ExecQuery2("select count(*) as EXISTE1 from usuarioa where usuario = ?", Array As String(user.Text))
	c.Position=0
	existe = c.GetString("EXISTE1")
	c.Close
	If existe > 0 Then
		c=skmt.ExecQuery("select USUARIO from usuarioa")
		c.Position=0
		usuario = c.GetString("USUARIO")
	Else
		usuario = "SINUSUARIO"
	End If
End Sub

'#if Java
'import java.util.concurrent.Callable;
'import com.google.android.gms.ads.identifier.AdvertisingIdClient;
'import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
'
'public static void GetAdvertisingId() {
'   BA.runAsync(processBA, mostCurrent, "advertisingid_ready", new Object[] {false, ""}
'       , new Callable<Object[]>() {
'                   @Override
'                   public Object[] call() throws Exception {
'                       String id = AdvertisingIdClient.getAdvertisingIdInfo(mostCurrent).getId();
'                       return new Object[] {true, id};
'                   }
'               }); }
'#End If

Sub copiaDB
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	Dim theDir As String = ""
	If Result Then
'		Private x As String
'		If File.ExternalWritable Then
'			x = File.DirRootExternal
'		Else
'			x = File.DirInternal
'		End If
		Dim theDir As String
		Try
			File.MakeDir(File.DirRootExternal,"kmts")
			theDir = "/kmts"
		Catch
			theDir = ""
		End Try
		Try
			File.Copy(File.DirInternal,"kmt.db",File.DirRootExternal&theDir, "intmex_kmt.db")
			ToastMessageShow("Listo, copiado a " & File.DirRootExternal&theDir & "/intmex_kmt.db", False)
		Catch
			ToastMessageShow("No se pudo hacer la copia: "&LastException, True)
		End Try
	Else
		ToastMessageShow("Sin permisos", False)
	End If
End Sub

Sub b_apk_Click
	StartService(appUpdater)
End Sub

'appUpdater - Mostramos el anuncio de que se esta descargando el nuevo apk
Sub muestraProgreso(mensaje As String)
	ProgressDialogShow(mensaje)
End Sub

'appUpdater - Ocultamos el anuncio de que se esta descargando el nuevo apk
Sub ocultaProgreso
	ProgressDialogHide
End Sub

Sub i_engrane_Click
	lv_server.Clear
	ime.HideKeyboard
	lv_server.AddSingleLine("http://keymon.net:1781")
'	lv_server.AddSingleLine("http://keymon.lat:1781")
	If user.Text = "KMTS1" Then lv_server.AddSingleLine("http://10.0.0.205:1781")
'	lv_server.AddSingleLine("http://40.123.36.38:1782")
	Log($"|${Starter.DBReqServer}|"$)
	l_server.Text = Starter.DBReqServer
	et_server.Text = Starter.DBReqServer
	Subs.panelVisible(p_appUpdate,0,0)
	If user.Text.trim = "KMTS1" Then b_importarBD.Visible = True Else b_importarBD.Visible = False
End Sub

Sub b_regesar_Click
	Subs.panelVisible(p_Main,0,0)
End Sub

Sub i_engrane_LongClick
	copiaDB
End Sub

Sub Entrar_LongClick
'	dim a as int = "a"
End Sub

Private Sub lv_server_ItemClick (Position As Int, Value As Object)
	Starter.DBReqServer = Value
	l_server.Text = Value
	et_server.Text = Value
	Starter.reinicializaReqManager(Value)
'	Starter.reqManager.Initialize(Me, Value)
	ToastMessageShow("Servidor modificado", False)
End Sub

Private Sub b_enviarbd_Click
	'	copiaDB
'	Sleep(1000)
	Dim FileName As String = "kmt.db"
	'copy the shared file to the shared folder
	Log("xxxxxx:"&Provider.SharedFolder)
	Sleep(1000)
	File.Copy(File.DirInternal, FileName, Provider.SharedFolder, FileName)
	Dim email As Email
	email.To.Add("soporte@keymonsoft.com")
	email.Subject = "Envio Base de datos INTMEX"
	email.Attachments.Add(Provider.GetFileUri(FileName))
'	email.Attachments.Add(Provider.GetFileUri(FileName)) 'second attachment
	Dim in As Intent = email.GetIntent
	in.Flags = 1 'FLAG_GRANT_READ_URI_PERMISSION
	StartActivity(in)
End Sub

Private Sub b_importarBD_Click
	Private FH As FileHandler
	FH.Initialize
	Wait For (FH.Load) Complete (Result As LoadResult) 'Abre un fileManager para seleccionar la base de datos a importar.
	File.Copy(Result.Dir, Result.FileName, File.DirInternal, "kmt.db") 'Copia la base de datos seleccionada al directorio interno.
	B4XPages.MainPage.skmt.Initialize(Starter.ruta,"kmt.db", True) 'Reiniciliza la base de datos con la recien importada.
	ToastMessageShow("¡BD importada!", False)
End Sub

Private Sub b_guardar_Click
	Starter.reinicializaReqManager(et_server.Text.Trim)
	p_appUpdate.Visible = False
End Sub