B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=9.85
@EndOfDesignText@
#Region Shared 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
	'###########################################################################################################
	'######################           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

Sub Class_Globals
	Private Root As B4XView
	Private xui As XUI
	Public login As B4XMainPage
	Dim rp As RuntimePermissions
	Public Provider As FileProvider
	
	Public principal As C_Principal 'Antes seleccion
	Public clientes As C_Clientes  'Antes Colonia
	Public cliente As C_Cliente 'Antes fila
	Public productos As C_Productos 'Antes colonia2
'	Public updateAvailable As C_updateAvailable
''	Public mapas As C_Mapas
''	Public nuevoCliente As C_NuevoCliente
	Public ticketsDia As C_TicketsDia 'Antes buscar
	Public noVenta As C_NoVenta 'Antes nopago
	Public nota As C_Nota 'Antes tarjeta
	Public promos As C_Promos
	Public historico As C_Historico 'Antes historico

	Dim reqManager As DBRequestManager
	Dim ultimaActualizacionGPS As String = 235959
	Dim almacen, ruta As String
	Dim user As EditText
	Dim pass As EditText
	Dim c As Cursor
	Dim D As Cursor
	Dim existe As String
	Dim paso1 As String
	Dim IMEI As String
	Dim alterno As String
	Private b_menu As Button
'	Dim PopupMenu As RSPopupMenu
	Dim cmd As DBCommand

	Private IMEN As EditText
	Private Entrar As Button
	Private Panel1 As Panel
	Private ImageView4 As ImageView
	Private E_SERVER As EditText
	Private B_SERVER As Button
	Private B_MACIMP As Button
	Private CUANTOS As String
	Private foto_g () As Byte
	
	Private ListView1 As ListView
	Private ImageView1 As ImageView
	Private Label1 As Label
	Private B_BorrarFinDia As Button
	Private b_fdCancelar As Button
	Private b_findiaOk As Button
	Private p_finDia As Panel
	Private et_autSup As EditText
	
	'prueba downloadfile
	Dim ProgressBar1 As ProgressBar
	Dim Label1 As Label
	Dim btnDownload As Button
	Dim btnCancel As Button
	Private p_download As Panel
	Private Label6 As Label
	Dim logger As Boolean = True
	
	Dim lat_gps, lon_gps As String
	Dim tipo_venta As String
	Dim bTerminarClicked As Boolean = False
	Private lv_server As ListView
	Private l_server As Label
	Public rutaBDBackup As String = ""
	Private b_envioBD As Button
	Dim kh As kms_helperSubs
	Private p_login As Panel
	Private l_version As Label
End Sub

Public Sub Initialize
	B4XPages.GetManager.LogEvents = True
	#if not(DEBUG)
		Starter.logger = False
	#end if
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
	If Not(Starter.Logger) Then logger = False
	Root = Root1
'	Root.LoadLayout("MainPage")
	Root.LoadLayout("login")
	B4XPages.SetTitle(Me, "Durakelo")
	login.Initialize
	B4XPages.AddPage("Login", login)
	principal.Initialize
	B4XPages.AddPage("Principal", principal)
	clientes.Initialize
	B4XPages.AddPage("Clientes", clientes)
	cliente.Initialize
	B4XPages.AddPageAndCreate("Cliente", cliente)
	productos.Initialize
	B4XPages.AddPage("Productos", productos)
'	updateAvailable.Initialize
'	B4XPages.AddPage("updateAvailable", updateAvailable)
'	mapas.Initialize
'	B4XPages.AddPage("Mapas", mapas)
'	nuevoCliente.Initialize
'	B4XPages.AddPageAndCreate("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)
'	checklist.Initialize
'	B4XPages.AddPage("CheckList", checklist)
'	ruta = Starter.ruta
	ruta = File.DirInternal
	kh.Initialize(Me, "kh", Starter.skmt)
	Provider.Initialize
'	If(FirstTime) Then
'	 g.Initialize("GPS")
'	End If
	' se crea o no el archivo de la base de ddatos de kmt
	'NOTAS SI SE MODIFICA LA ESTRUCTURA SE QUITA EL IF Y SE VA DIRECTO A LA SENTENCIA FILE.COPY PARA QUE
	'TOME LA NUEVA ESTRUCTURA ES MUY IMPORTANTE TENER EL IF DE LO CONTRARIO SOLO LO ESCRIBE UNA VEZ Y LO BORRA
	'SI SE REGRESA A ESTE ACTIVIDAD.
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
'	Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
	kh.guardaAppInfo
	Dim sDate, sTime As String
	DateTime.DateFormat = "yyyyMMdd"
	sDate=DateTime.Date(DateTime.Now)
	
	Starter.skmt.ExecNonQuery("DROP TABLE IF EXISTS PEDIDO3")
'	skmt.ExecNonQuery("DROP VIEW TOTAL_MARCAS")
	
	Starter.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_GUNAPROD2 GROUP BY CAT_GP_CLASIF, CAT_GP_ID")
	Starter.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")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_EXHIBIDORES (CAT_EX_ID TEXT, CAT_EX_TIPO TEXT, CAT_EX_VALOR TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE PEDIDO3 (PE_PRECIO2 TEXT,PE_TIPO TEXT,PE_FOLIO NUMERIC,PE_DESC NUMERIC,PE_COSTO_SIN TEXT,PE_RUTA TEXT,PE_CEDIS TEXT,PE_COSTO_TOT NUMERIC,PE_COSTOU NUMERIC,PE_CANT NUMERIC,PE_PRONOMBRE TEXT,PE_PROID TEXT,PE_CLIENTE TEXT,PE_FECHA TEXT,PE_USUARIO TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS RUTA_GPS(FECHA INTEGER, LAT TEXT, LON TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CLIENTE_IMPRESO (CI_CUENTA TEXT)")
	kh.agregaColumna(Starter.skmt, "kmt_info", "impresion", "TEXT")
	If sDate = "20190523" Then
		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",Starter.skmt))
	End If
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_ENCUESTA (HE_CLIE TEXT, HE_RES TEXT, HE_FECHA TEXT, HE_TIPO TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_ENCUESTA2 (HE_CLIE TEXT, HE_RES TEXT, HE_FECHA TEXT, HE_TIPO TEXT, HE_PRECIO TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_ENCUESTA_PREGUNTA (CAT_EP_ID TEXT,CAT_EP_IDTIPOPREGUNTA TEXT,CAT_CE_DESCRIPCION TEXT,CAT_EP_PREGUNTA TEXT,CAT_EP_RES1_PRED TEXT,CAT_EP_RES2_PRED TEXT,CAT_EP_RES3_PRED TEXT,CAT_EP_ORDEN_PREGUNTA TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_ENCUESTA_PREGUNTA5P (CAT_EP_ID TEXT,CAT_EP_IDTIPOPREGUNTA TEXT,CAT_CE_DESCRIPCION TEXT,CAT_EP_PREGUNTA TEXT,CAT_EP_RES1_PRED TEXT,CAT_EP_RES2_PRED TEXT,CAT_EP_RES3_PRED TEXT,CAT_EP_ORDEN_PREGUNTA TEXT)")
	
	c=Starter.skmt.ExecQuery2("select count(*) as CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SERVER"))
	c.Position =0
	If c.GetString("CUANTOS") = 0 Then
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("SERVER",Starter.DBReqServer))
	Else
		c=Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SERVER"))
		c.Position =0
		Starter.DBReqServer = c.GetString("CAT_VA_VALOR")
	End If
	Dim P As PhoneId
	'user.Text = P.GetDeviceId
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_READ_PHONE_STATE)
	Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		Dim P As PhoneId
		'user.Text = P.GetDeviceId
		IMEI = P.GetDeviceId
		IMEI = ""
	Else
		If logger Then Log("Sin permisos para leer los datos del celular")
	End If
	
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
	Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		StartService(Tracker)
		Log("Start Tracker")
	End If
	p_login.Height = Root.Height
	p_login.Width = Root.Width
	
End Sub

Sub B4XPage_Appear
	l_version.Text = Application.VersionName
'	copiaDB
'	server = "http://10.0.0.205:1782"

	reqManager.Initialize(Me, Starter.DBReqServer)
	Log(Starter.DBReqServer)
'	If g.GPSEnabled=False Then
	'    	  ToastMessageShow("Habilitar el GPS", True)
	'    	  StartActivity(g.LocationSettingsIntent)
	'    Else
	'    	  g.Start(0,0)
	'    End If
'	 user.Text ="GPS"
	c = Starter.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
		cmd.Initialize
		cmd.Name = "select_fechat"
		reqManager.ExecuteQuery(cmd , 0, "fecha")

		'Msgbox("AJUSTAR FECHA","AVISO")
		B4XPage_Appear
	Else
		c = Starter.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 = "yyyyMMddHHmm"
		sDate=DateTime.Date(DateTime.Now)
		
		'Msgbox("aaa"& sDate,"aviso")
		If c.GetString("CAT_VA_VALOR") > sDate & sTime Then
'			Msgbox("AJUSTAR LA FECHA YA QUE ES MENOR AL SISTEMA " & " "& c.GetString("CAT_VA_VALOR") & " " & sDate & sTime ,"AVISO")
			DateTime.TimeFormat = "MM/dd/yyyyHH:mm:ss"
			B4XPage_Appear
		End If
		DateTime.TimeFormat = "MM/dd/yyyyHH:mm:ss"
	End If
	c.Close
	c = Starter.skmt.ExecQuery2("select count(*) as CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("CODIGO"))
	c.Position =0
	CUANTOS = c.GetString("CUANTOS")
	c.Close
	If CUANTOS > 0 Then
		c = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("CODIGO"))
		c.Position =0
		If c.GetString("CAT_VA_VALOR") = "743" Then
			Entrar.Visible = True
		End If
		c.Close
	Else
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("CODIGO","0"))
	End If
	
	c=Starter.skmt.ExecQuery2("select COUNT(*) AS CUANTOS  from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("MACIMP"))
	c.Position =0
	If c.GetString("CUANTOS") = 0 Then
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MACIMP","0"))
	End If
	
	c=Starter.skmt.ExecQuery("select COUNT(*) AS CUANTOS FROM VERSION")
	c.Position= 0
	
	If c.GetString("CUANTOS") = 0 Then
		Starter.skmt.ExecNonQuery("delete from VERSION")
		Starter.skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object ("2.6"))
	End If
	c.Close
	
	c=Starter.skmt.ExecQuery("select NOVERSION FROM VERSION")
	c.Position = 0
	
	If c.GetString("NOVERSION")  <> "2.6" Then
'		Msgbox("VERSION INCORRECTA SOLICITAR O DESCARGAR LA NUEVA","ALERTA")
		B4XPage_Appear
	End If
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
	Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		StartService(Tracker)
		If logger Then Log("Start Tracker")
	Else
		ToastMessageShow("No permission", True)
	End If
	Starter.usuario = kh.traeUsuarioDeDB
'	dameUsuario 'Obtenemos el usuario registrado
	CallSubDelayed(FirebaseMessaging, "SubscribeToTopics")
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 = "ROOT" 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 (pass.Text))
		B4XPages.ShowPage("Principal")
	End If

	c=Starter.skmt.ExecQuery2("select count(*) as EXISTE1 from usuarioa where usuario = ?", Array As String(user.Text))
	c.Position=0
	existe = c.GetString("EXISTE1")
    
	'existe = 1
	If existe = 0 Then
		'skmt.ExecNonQuery("delete from usuarioa")
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "select_usuario_guna_DUR"
		cmd.Parameters = Array As Object(user.Text, pass.Text)
		reqManager.ExecuteQuery(cmd , 0, "usuario")
		
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "select_version_DUR"
		reqManager.ExecuteQuery(cmd , 0, "version")
	Else
		B4XPages.ShowPage("Principal")
	End If
	
End Sub

Sub JobDone(Job As HttpJob)
	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))
					If CAT_VE_VERSION <> "2.6" Then
						Msgbox("VERSION INCORRECTA SOLICITAR O DESCARGAR LA NUEVA","ALERTA")
						B4XPage_Appear
					End If
				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 = "fecha" Then 'query tag
				For Each records() As Object In result.Rows
					Dim FECHA_HOY As String = records(result.Columns.Get("FECHA"))
					Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FECHA"))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FECHA",FECHA_HOY))
				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" & IMEI 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))
			Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("NUMERO_PEDIDO"))
			Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("NUMERO_PEDIDO",0))
			B4XPages.ShowPage("Principal")
		Else If name  = "OKExpirado"& IMEI Then
			Msgbox("Usuario Expirado llamar al administrador","")
		Else If name = "OKCancelado"& IMEI Then
			Msgbox("Usuario Cancelado llamar al administrador","")
		Else
			Msgbox("Usuario o password No validos","")
		End If
		paso1 = 0
	End If
End Sub

'Sub Activity_KeyPress (key As Int) As Boolean
'	' BACK key pressed
'	If key=KeyCodes.KEYCODE_BACK Then
'		' I want to capture the key here so I return True
'		'StartActivity(Main)
'		ExitApplication
'		'Return True
'	End If
'	' Returning False signals the system to handle the key
'	Return False
'End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
	ExitApplication
	Return False
End Sub

Sub GPS_LocationChanged (Location1 As Location)
	If user.text = "GPS" Then
		'user.Text=Location1.ConvertToMinutes(Location1.Latitude)
		'pass.text=Location1.ConvertToMinutes(Location1.Longitude)
		user.Text=Location1.Latitude
		pass.text=Location1.Longitude
		'btnTakePicture.Enabled = True
		's.ExecNonQuery2("INSERT INTO  HIST_GPS (HGDATE,HGLAT, HGLON) VALUES(?,?,?) ", Array As Object (sDate & sTime, lat_gps, lon_gps))
	End If
End Sub

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

Sub PDF_Click

End Sub

Sub user_EnterPressed
	If user.Text = "CODIGO" Then
		IMEN.Visible = True
		user.Text = ""
	End If		
End Sub

Sub ImageView4_Click
	Entrar.Visible = False
	ListView1.Clear
	Dim Label1 As Label
	Label1 = ListView1.SingleLineLayout.Label
	Label1.TextSize = 20
	Label1.TextColor = Colors.Black
	ListView1.AddSingleLine(Starter.DBReqServer)

	c=Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SERVER"))
	c.Position =0
	E_SERVER.text = c.GetString("CAT_VA_VALOR")
'	Panel1.Visible = True
	kh.panelVisible(Panel1, 0, 0)
End Sub

Sub B_SERVER_Click
	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",E_SERVER.text))
	reqManager.Initialize(Me, E_SERVER.text.trim)
	Starter.DBReqServer = E_SERVER.text.trim
	Panel1.Visible = False
	Entrar.Visible = True
End Sub

Sub B_FECHA_Click
	Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FECHA"))
	Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("MACIMP"))
	Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MACIMP","0"))
	Panel1.Visible = False
End Sub

Sub ListView1_ItemClick (Position As Int, Value As Object)
	E_SERVER.text = Value
End Sub

Sub B_IMPRESORA_Click
	Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("MACIMP"))
	Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MACIMP","0"))
	Panel1.Visible = False
End Sub

Sub dameUsuario
	c=Starter.skmt.ExecQuery("select count(*) as EXISTE1 from usuarioa")
	c.Position=0
	existe = c.GetString("EXISTE1")
	c.Close
	If existe > 0 Then
		c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
		c.Position=0
		Starter.usuario = c.GetString("USUARIO")
	Else
		Starter.usuario = "SINUSUARIO"
	End If
End Sub

'Copia la base de datos del almacenamiento interno al externo en el directorio kmts
Sub copiaDB
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
	Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		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,"dura_kmt.db")
			ToastMessageShow("Listo, copiada a " & File.DirRootExternal&theDir & "/dura_kmt.db", False)
			LogColor("copiado", Colors.red)
		Catch
			ToastMessageShow("No se pudo hacer la copia: "&LastException, True)
			LogColor("no copiado", Colors.red)
		End Try
'		Log("rootExternal="&p)
'		Log("File.DirInternal="&File.DirInternal)
'		Log("File.DirRootExternal="&File.DirRootExternal)
	Else
		ToastMessageShow("Sin permisos", True)
	End If
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("cheveguerra@gmail.com")
	email.Subject = "subject"
	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