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
	'###########################################################################################################
	'######################           PULL         #############################################################
	'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=git&Args=pull 
	'###########################################################################################################
	'######################           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
	'###########################################################################################################
#End Region

'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip

Sub Class_Globals
	Dim rp As RuntimePermissions
	Private Root As B4XView
	Private xui As XUI
	Private Root As B4XView
	Public rp As RuntimePermissions
	Public login As B4XMainPage
	Public principal As C_Principal
	Public clientes As C_Clientes
	Public cliente As C_Cliente
'	Public foto As C_Foto
	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 pedidos As C_Pedidos
	Public buscar As C_Buscar
'	Public historico As C_Historico
	Public detalleVenta As C_DetalleVenta
	Public detalle_promo As C_Detalle_Promo
	Public picking As C_picking
	Dim reqManager As DBRequestManager
'	Dim ruta As String
	Dim usuario As String
	Dim logger As Boolean = True
	Dim lat_gps, lon_gps As String
'	Dim skmt As SQL
	Dim usuario As String
	Dim server As String
	Dim montoActual, clientesTotal, clientesVenta, clientesRechazo, clientesVisitados, almacen, rutaPreventa, CANTIDADPROD As String
	Dim ultimaActualizacionGPS As String = 235959
	Dim fechaRuta As String
'	Public wsServerLink As String = "ws://187.189.244.154:51042/push/b4a_ws2"
'	Public wsServerLink As String = "ws://10.0.0.214:51042/push/b4a_ws2"
	Dim srvIp As String
	Dim phn As Phone
	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
	Private Label1 As Label
	Dim server As String
	Private p_principal As Panel
	Private Entrar As Button
	Public tabulador As C_tabulador
	Dim batt As Int
	Dim porVisitar, entregas, rechazos, montoEntregado, montoRechazado As String
	Private p_appUpdate As Panel
	Private i_engrane As ImageView
	Private b_server As Button
	Private b_apk As Button
	Private b_envioBD As Button
	Private b_regesar As Button
	Private et_server As EditText
	Private p_serverList As Panel
	Private lv_server As ListView
	Public Provider As FileProvider
	Public rutaBDBackup As String = ""
	Dim rutarep As String
	Private p_ruteo As Panel
'	Private lv_algoritmo As ListView
'	Private lv_matriz As ListView
	Private s_algoritmo As Spinner
	Private s_matriz As Spinner
	Dim in As Intent
	Dim intentUsado As Boolean = False
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)
	Root = Root1
	B4XPages.GetManager.LogEvents = True
	Root.LoadLayout("login")
	B4XPages.SetTitle(Me, "Guna Reparto")
	login.Initialize
	B4XPages.AddPage("Login", login)
	principal.Initialize
	B4XPages.AddPage("Principal", principal)
	clientes.Initialize
	B4XPages.AddPage("Clientes", clientes)
	cliente.Initialize
	B4XPages.AddPage("picking", picking)
	picking.Initialize
	B4XPages.AddPage("Cliente", cliente)
'	foto.Initialize
'	B4XPages.AddPage("Foto", foto)
	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)
	pedidos.Initialize
	B4XPages.AddPage("Pedidos", pedidos)
	buscar.Initialize
	B4XPages.AddPage("Buscar", buscar)
'	historico.Initialize
'	B4XPages.AddPage("Historico", historico)
	detalleVenta.Initialize
	B4XPages.AddPage("DetalleVenta", detalleVenta)
	detalle_promo.Initialize
	B4XPages.AddPage("Detalle_Promo", detalle_promo)
	tabulador.Initialize
	B4XPages.AddPage("tabulador", tabulador)
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS TABULADOR_MONEDAS(VEINTE TEXT, DIEZ TEXT, CINCO TEXT, DOS TEXT, PESO TEXT, CENTAVO TEXT, TOTAL TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS TABULADOR_BILLETES(MIL TEXT, QUINIENTOS TEXT, DOCIENTOS TEXT, CIEN TEXT, CINCUENTA TEXT, VEINTE TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_VENTAS2 (HVD_PARCIAL TEXT, HVD_RECHAZO TEXT, HVD_NUM_REGISTRO TEXT, HVD_NUM_TICKET TEXT, HVD_PROID TEXT, HVD_CODPROMO TEXT, HVD_FECHA TEXT, HVD_ESTATUS TEXT, HVD_CLIENTE TEXT, HVD_PRONOMBRE TEXT, HVD_CANT TEXT, HVD_COSTO_TOT TEXT)")
'	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS VENTAS (V_FECHA TEXT, V_CLIENTE TEXT, V_CLIENTE_ORIG TEXT, V_PRODNOMBRE TEXT, V_PRODID TEXT, V_CANTIDAD TEXT, V_PRECIO TEXT, V_TOTAL TEXT, V_PRODREGISTRO TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS RECHAZOS (R_FECHA TEXT, R_CLIENTE TEXT, R_CLI_ORIG TEXT, R_PRODID TEXT, R_CANT TEXT, R_RECHAZO INT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS VENTAS (V_FECHA TEXT, V_CLIENTE TEXT, V_CLI_ORIG TEXT, V_PRODID TEXT, V_CANT TEXT, V_RECHAZO INT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS PAGARES (NOTA TEXT, CLIENTE TEXT, ALMACEN TEXT, SALDO_PENDIENTE TEXT, RUTA_PREVENTA TEXT, REPARTO TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS PAGARES_NUEVOS (NOTA TEXT, CLIENTE TEXT, ALMACEN TEXT, MONTO TEXT, RUTA_PREVENTA TEXT, REPARTO TEXT, FECHA TEXT)")
	Subs.agregaColumna("REPARTO", "REP_PRODREGISTRO", "TEXT")
	Subs.agregaColumna("PICKING_REPARTO", "FECHA", "TEXT")
	Subs.agregaColumna("kmt_info", "SECUENCIA", "INT")
	Subs.agregaColumna("kmt_info", "CAT_CL_LIMITECREDITO", "TEXT")
	Subs.agregaColumna("REPARTO", "REP_PRODID", "TEXT")
	Subs.agregaColumna("REPARTO", "REP_CLI_ORIG", "TEXT")
	Subs.agregaColumna("REPARTO", "REP_PRECIO", "TEXT")
	Subs.agregaColumna("REPARTO", "REP_RECHAZO", "INTEGER")
	Subs.agregaColumna("REPARTO", "REP_IDALMACEN", "TEXT")
	Subs.agregaColumna("RECHAZOS", "R_PRECIO", "TEXT")
	Subs.agregaColumna("VENTAS", "V_PRECIO", "TEXT")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS RUTAA (RUTAA TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS wayPoints (codigo TEXT, indice INT)")
	Subs.agregaColumna("kmt_info", "CAT_CL_IDALMACEN", "TEXT")
	Subs.agregaColumna("HIST_VENTAS", "HVD_IDALMACEN", "TEXT")
	Subs.agregaColumna("HIST_VENTAS2", "HVD_IDALMACEN", "TEXT")
	Subs.agregaColumna("NOVENTA", "NV_IDALMACEN", "TEXT")
	Subs.agregaColumna("RECHAZOS", "R_IDALMACEN", "TEXT")
	Subs.agregaColumna("VENTAS", "V_IDALMACEN", "TEXT")
'	Dim server As String = "http://11.0.0.151:1782"
	Dim server As String = "http://187.189.244.154:1782"
'	Dim server As String = "http://11.0.0.12:1782"
'	server = "http://10.0.0.205:1782"
'	server = "http://11.0.0.44:1782"
	reqManager.Initialize(Me, B4XPages.MainPage.server)
	LogColor($"ReqServer = ${B4XPages.MainPage.server}"$, Colors.red)
	Label1.Text = Application.VersionName
'	Dim P As PhoneId
	Log("provider")
	Provider.Initialize
	s_algoritmo.AddAll(Array As String("Nearest Neighbor", "Nearest Insertion"))
	s_algoritmo.TextSize = 13
	s_matriz.AddAll(Array As String("OSRM", "LOCAL"))
	s_matriz.TextSize = 13
	Subs.centraPanel(p_ruteo, Root.Width)
'	lv_algoritmo.AddSingleLine2("Nearest Neighbor","NN")
'	lv_algoritmo.AddSingleLine2("Nearest Insertion", "NI")
'	lv_algoritmo.SingleLineLayout.Label.TextColor = Colors.black
'	lv_algoritmo.SingleLineLayout.Label.TextSize = 11
'	lv_matriz.AddSingleLine("OSRM")
'	lv_matriz.AddSingleLine("LOCAL")
'	lv_matriz.SingleLineLayout.Label.TextColor = Colors.black
'	lv_matriz.SingleLineLayout.Label.TextSize = 11
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_READ_PHONE_STATE)
'	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then
'		IMEN.Text = "" 'P.GetDeviceId
'		IMEI = "" 'P.GetDeviceId
'	End If
	Subs.agregaColumna("PICKING_REPARTO","ESTATUS","INT")
End Sub

Sub B4XPage_Appear
	importaBDDesdeWhatsApp
	If Starter.muestraProgreso = 1 Then
		muestraProgreso("Descargando actualización")
		Starter.muestraProgreso = 0
	End If
	Subs.centraPanel(p_principal, Root.Width)
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
'	LogColor("Start Tracker1", Colors.red)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		StartService(Tracker)
'		LogColor("Start Tracker", Colors.red)
	Else
		ToastMessageShow("No permission", True)
		Log("Sin permisos")
	End If
'	LogColor("Start Tracker3", Colors.red)
	c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
	If c.RowCount > 0 Then
'		c.Position=0
'		c=skmt.ExecQuery("select USUARIO from usuarioa")
		c.Position=0
		usuario = c.GetString("USUARIO")
	End If
	c.Close
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
'	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then
'		Log("Con permisos de escritura externa")
'	End If
	Private al As String = "Nearest Neighbor"
	If Subs.traeAlgoritmoRuteo <> "NN" Then al = "Nearest Insertion"
	s_algoritmo.SelectedIndex = s_algoritmo.IndexOf(al)
	s_matriz.SelectedIndex = s_matriz.IndexOf(Subs.traeMatrizRuteo)
End Sub

'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.

Sub Entrar_Click
	If user.Text = "x" And pass.Text = "" Then
		user.Text = "CAPACITACIONR"
	End If
	If pass.Text = "YA" Then
		Starter.skmt.ExecNonQuery("delete from usuarioa")
		Starter.skmt.ExecNonQuery("delete from VERSION")
		Starter.skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object("ROOT", "ROOT"))
		Starter.skmt.ExecNonQuery("delete from cat_almacen")
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (user.Text))
		Starter.skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object ("2.1"))
'		principal.B_REGRESA_Click
'		B4XPages.MainPage.principal.Subir.Visible = True
		B4XPages.ShowPage("Principal")
	Else
		c=Starter.skmt.ExecQuery2("select count(*) as EXISTE1 from usuarioa where usuario = ?", Array As String(user.Text))
		c.Position=0
		existe = c.GetString("EXISTE1")
		c.Close
		'existe = 1
		If existe = 0 Then
			'skmt.ExecNonQuery("delete from usuarioa")
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "select_usuario_guna_REPG2"
			cmd.Parameters = Array As Object(user.Text, pass.Text)
			reqManager.ExecuteQuery(cmd , 0, "usuario")
	
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "select_version_GUNA2"
			reqManager.ExecuteQuery(cmd , 0, "version")
		Else
'			principal.B_REGRESA_Click
			B4XPages.ShowPage("Principal")
		End If
	End If
End Sub

Sub JobDone(Job As HttpJob)
	Log("JobDone MainPage: " & Job.Success)
	If Job.Success = False Then
		ToastMessageShow("Error: " & Job.ErrorMessage, True)
	Else
		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "version" Then 'query tag
				For Each records() As Object In result.Rows
					Starter.skmt.ExecNonQuery("delete from VERSION")
					Dim CAT_VE_VERSION As String = records(result.Columns.Get("CAT_VE_VERSION"))
					Starter.skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object (CAT_VE_VERSION))
				Next
			End If
		End If
	 
		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			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
		End If
	 
		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			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"))
				Next
				paso1 = 1
			End If
		End If
		Job.Release
	End If
	
	If paso1 = 1 Then
		If name = "OKActivo" Then
			Starter.skmt.ExecNonQuery("delete from usuarioa")
			Starter.skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object(user.Text, pass.Text))
			Starter.skmt.ExecNonQuery("delete from cat_almacen")
			Starter.skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (ID_ALMACEN))
			B4XPages.ShowPage("Principal")
		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
	End If
End Sub

Private Sub i_engrane_Click
	p_appUpdate.Width = Root.Width
	p_appUpdate.Height = Root.Height
	Subs.centraPanel(p_serverList, Root.Width)
	Subs.centraBoton(b_server, Root.Width)
	Subs.centraBoton(b_apk, Root.Width)
	Subs.centraBoton(b_envioBD, Root.Width)
	Subs.centraBoton(b_regesar, Root.Width)
	Subs.centraBoton(b_server, p_serverList.Width)
	lv_server.Clear
	lv_server.AddSingleLine("http://keymon.lat:1782")
	If user.Text = "KMTS1" Then
		lv_server.AddSingleLine("http://11.0.0.222:1782")
		p_ruteo.Visible = True
	End If
'	l_server.Text = Starter.server
	et_server.Text = server
	Subs.panelVisible(p_appUpdate, 0, 0)
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
'	Log("closreq")
	If p_appUpdate.Visible Then
		p_appUpdate.Visible = False
	Else
		Sleep(0)
		ExitApplication
	End If
	Return False
End Sub

Private Sub b_regesar_Click
	p_principal.Visible = True
	p_appUpdate.Visible = False
End Sub

'Enviamos la base de datos por correo o Whatsapp
Private Sub b_envioBD_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 = "Base de datos para revisión"
	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_apk_Click
	StartService(appUpdater)
End Sub

Private Sub b_server_Click
	Log("Guardar servidor")
	Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("SERVER"))
	Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("SERVER",et_server.text))
	B4XPages.MainPage.server = et_server.text
	Starter.server = B4XPages.MainPage.server
	If logger Then Log("Inicializamos reqManager con " & B4XPages.MainPage.server)
	reqManager.Initialize(Me, B4XPages.MainPage.server)
	LogColor($"ReqServer = ${B4XPages.MainPage.server}"$, Colors.red)
	reinicializaReqManager
	p_appUpdate.Visible = False
'	Entrar.Visible = True
End Sub

Private Sub lv_server_ItemClick (Position As Int, Value As Object)
	server = Value
'	l_server.Text = Value
	et_server.Text = Value
	reqManager.Initialize(Me, Value)
	LogColor($"ReqServer = ${Value}"$, Colors.red)
	ToastMessageShow("Servidor modificado", False)
End Sub

Sub reinicializaReqManager
	reqManager.Initialize(Me, B4XPages.MainPage.server)
	If logger Then Log(B4XPages.MainPage.server)
	LogColor($"ReqServer = ${B4XPages.MainPage.server}"$, Colors.red)
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

'Private Sub lv_algoritmo_ItemClick (Position As Int, Value As Object)
'	Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("ALGORITMO_RUTEO"))
'	Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("ALGORITMO_RUTEO",Value))
'End Sub
'
'Private Sub lv_matriz_ItemClick (Position As Int, Value As Object)
'	Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("MATRIZ_RUTEO"))
'	Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MATRIZ_RUTEO",Value))
'End Sub

Private Sub s_algoritmo_ItemClick (Position As Int, Value As Object)
	Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("ALGORITMO_RUTEO"))
	Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("ALGORITMO_RUTEO",Value))
	Log(Value)
End Sub

Private Sub s_matriz_ItemClick (Position As Int, Value As Object)
	Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("MATRIZ_RUTEO"))
	Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MATRIZ_RUTEO",Value))
	Log(Value)
End Sub


' Se revisa si hay una intención (intent) de abrir una base de datos y si es así, entonces se importa esa base de datos.
Sub importaBDDesdeWhatsApp
	Log("importams bdwa")
'	Private tmpBDWA As Boolean = traeUsarIntentBDWA
	If Not(in.IsInitialized) Then in = B4XPages.GetNativeParent(B4XPages.MainPage).GetStartingIntent ' Si se usa esta funcion en Mainpage, se pone "Me" en lugar de B4XPages.MainPage.
	If Not(intentUsado) And in <> Null Then
'		Log(in)
		Log(7654)
		intentUsado = True
'			Log(in.As(String))
		If in.GetData <> Null Then
			Log(98765)
			Dim XmlData As String
			XmlData = in.GetData
			Try
				Dim OutStr As OutputStream = File.OpenOutput(File.DirInternal,"kmt.db",False)
				Dim InStr As InputStream = File.OpenInput("ContentDir",XmlData)
				File.Copy2(InStr,OutStr)
				LogColor("BD copiada a interna.", Colors.Blue)
				OutStr.Close
				If in.As(String).Contains("whatsapp") Then ToastMessageShow("BD cargada desde Whatsapp", False)
			Catch
				Log(LastException)
			End Try
'				ExitApplication
'			Starter.skmt.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'IMPORTAR_BD_WA'")
'			Starter.skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('IMPORTAR_BD_WA', '${tmpBDWA}')"$)
			Private a As Cursor = Starter.skmt.ExecQuery($"select CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'APP_NAME'"$)
			If a.RowCount > 0 Then
				a.Position = 0
				ToastMessageShow($"BD de "${a.GetString("CAT_VA_VALOR")}" cargada."$, True)
			End If
			a = Starter.skmt.ExecQuery($"select * from usuarioa"$)
			If a.RowCount > 0 Then
				a.Position = 0
				B4XPages.MainPage.user.Text = a.GetString("USUARIO")
				B4XPages.MainPage.pass.Text = a.GetString("PASS")
			End If
		End If
	End If
End Sub