B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Activity
Version=9.3
@EndOfDesignText@
#Region  Activity Attributes 
	#FullScreen: False
	#IncludeTitle: False
#End Region

'Activity module
Sub Process_Globals
	Dim GPS As GPS
	Dim rp As RuntimePermissions
	Dim ruta As String
	Dim skmt As SQL
	Dim c As Cursor
	Dim c2 As Cursor
	Dim c22 As Cursor
	Dim c3 As Cursor
	Private xui As XUI 'ignore
End Sub

Sub Globals
	Private gmap As GoogleMap
	Private MapFragment1 As MapFragment
	Dim Latitud As Double = 0
	Dim Longitud As Double = 0
	Dim Lat2 As Double = 0
	Dim Lon2 As Double = 0
	Dim p1, p2 As Location
	Dim Distance As Float
	Dim boton1 As Button
	Dim HUE_BLUE As Float
	Dim HUE_RED As Float
	Dim HUE_GREEN As Float
	Private B_AZUL As Button
	Private B_ROJO As Button
	Private B_VERDE As Button
	Private B_TODOS As Button
	Dim Tienda As String
	Dim LatitudRu As Double
	Dim LongitudRU As Double
	Dim LIST_AZUL As List
	Dim LIST_ROJO As List
	Dim LIST_VERDE As List
	Dim MARK_AZUL As Marker
	Dim MARK_ROJO As Marker
	Dim MARK_VERDE As Marker
	Dim MARK_CEDIS As Marker
	Dim rojo As String
	Dim azul As String
	Dim verde As String
	Dim todos As String
	Dim NumSerie As Int
	Dim OnInfoWindowClickListener1 As OnInfoWindowClickListener
	Dim GoogleMapEXTRA As GoogleMapsExtras
	Dim CODIGO As String
	Private SEMANA As String
	Private p_transparenciaIniciaInicioFinVenta As Panel
	Private b_inicioVenta As Button
	Private b_finVenta As Button
	Private p_inicioFinVenta As Panel
	Private p_guardarPeso As Panel
	Private et_guardarPeso As EditText
	Private b_guardarPeso As Button
	Private p_botonesGuardarPeso As Panel
	Private b_noVenta As Button
	Private p_noVenta As Panel
	Private b_cancelaNoVenta As Button
	Private b_guardaNoVenta As Button
	Private p_botonesNoVenta As Panel
	Private Panel5 As Panel
	Private et_comentarioNoVenta As EditText
	Private r_opcion5 As RadioButton
	Private r_opcion4 As RadioButton
	Private r_opcion3 As RadioButton
	Private r_opcion2 As RadioButton
	Private r_opcion1 As RadioButton
	Private l_NoVenta As Label
	Dim motivo As String
	Private l_venta As Label
	Private camEx As CameraExClass
	Dim fototomada As String = "0"
	Private frontCamera As Boolean = False
	Private p_camara As Panel
	Private b_cam As Button
	Private b_foto_inci As Button
	Private p_cam As Panel
	Dim sDate As String
	Dim sTime As String
	Private p_camara2 As Panel
	Private nombreFoto As String
	Dim fotoCerrado As String = ""
End Sub

Sub Activity_Create(FirstTime As Boolean)
	Activity.LoadLayout("MAPA_RUTAS")
'	If File.ExternalWritable Then
'		ruta = File.DirDefaultExternal
'	Else
	p_transparenciaIniciaInicioFinVenta.top = 0 : p_transparenciaIniciaInicioFinVenta.Left = 0
	p_transparenciaIniciaInicioFinVenta.Height = Activity.Height : p_transparenciaIniciaInicioFinVenta.Width = Activity.Width
	Subs.centraPanel(p_inicioFinVenta, Activity.Width)
	p_guardarPeso.Top = p_inicioFinVenta.top : p_guardarPeso.left = p_inicioFinVenta.left
	Subs.centraPanel(p_noVenta, Activity.Width)
	
	ruta = File.DirInternal
'	End If
	If File.Exists(ruta, "kmt.db") = False Then
		File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db")
	End If
	skmt.Initialize(ruta,"kmt.db", True)
	'GPS
	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")
		If MapFragment1.IsGooglePlayServicesAvailable = False Then
			ToastMessageShow("Please install Google Play Services.", True)
		End If
	Else
		ToastMessageShow("No permission", True)
		B4XPages.ShowPage("Principal")
	End If
'	If(FirstTime) Then
'		Starter.GPS.Initialize("GPS")
'	End If

	
	'Boton velocidad'
'	boton1.Initialize(0)
'	boton1.Text = 0 &" "&"km/h"
'	boton1.TextColor = Colors.Red
'	boton1.TextSize = 15
'	Activity.AddView(boton1, 40%x, 5dip, 25%x, 40dip)
	'Fin Boton velocidad'
	'MARK_CEDIS.IsInitialized
	MARK_AZUL.IsInitialized
	MARK_ROJO.IsInitialized
	MARK_VERDE.IsInitialized
	LIST_AZUL.Initialize
	LIST_ROJO.Initialize
	LIST_VERDE.Initialize
	verde = 0
	azul = 0
	rojo = 0
	todos = 1
	c=skmt.ExecQuery2("select count(*) AS CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SEMANA"))
	c.Position =0
	SEMANA = c.GetString("CUANTOS")
	c.Close
	If SEMANA > 0 Then
		c=skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SEMANA"))
		c.Position =0
		SEMANA = c.GetString("CAT_VA_VALOR")
		c.Close
	End If
End Sub

Sub Activity_Resume
	Log("MAPA_RUTAS RESUME")
	InitializeCamera
	fotoCerrado = ""
	Starter.rp.Check(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
	Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		If Starter.GPS.GPSEnabled = False Then
			ToastMessageShow("Debe Activar el GPS del Equipo.", True)
			StartActivity(Starter.GPS.LocationSettingsIntent)
		Else
			Starter.GPS.Start(0, 0)
		End If
	End If
	LIST_AZUL.Initialize
	LIST_ROJO.Initialize
	LIST_VERDE.Initialize
	verde = 0
	azul = 1
	rojo = 0
	todos = 0
	If Subs.nosQuedamosEnVenta Then
		Dim enVentaUsuario As String = ""
		Dim enVentaPagina As String = ""
		Private ev As Cursor = Starter.skmt.ExecQuery("select * from cat_variables where cat_va_descripcion = 'EN_VENTA_USUARIO' or cat_va_descripcion = 'EN_VENTA_PAGINA'")
		If ev.RowCount > 0 Then
			For i = 0 To ev.RowCount - 1
				ev.Position = i
				If ev.GetString("CAT_VA_DESCRIPCION") = "EN_VENTA_USUARIO" Then
					enVentaUsuario = ev.GetString("CAT_VA_VALOR")
				Else If ev.GetString("CAT_VA_DESCRIPCION") = "EN_VENTA_PAGINA" Then
					enVentaPagina = ev.GetString("CAT_VA_VALOR")
				End If
			Next
			ventaIniciada
		End If
	End If
	p_camara.Top = 0 : p_camara.Left = 0
	p_camara.Width = Activity.Width : p_camara.Height = Activity.Height
	Subs.centraPanel(p_camara2, Activity.Width)
End Sub

Sub MapFragment1_Ready
'	Log("ENTRANDO MapFragment1_Ready")
	gmap = MapFragment1.GetMap
	gmap.IsInitialized
'	todos = 1
	'permisos

	rp.CheckAndRequest(rp.PERMISSION_ACCESS_FINE_LOCATION)
	Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
	gmap.MyLocationEnabled = Result
		
	Dim JavaMapsObject As JavaObject
	JavaMapsObject = gmap.GetUiSettings
	JavaMapsObject.RunMethod("setMapToolbarEnabled", Array As Object(True))
	'''''''----------------------------MARKER AZUL - POR VISITAR
	If azul = 1 Or todos = 1 Then
		c.IsInitialized
		c=skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_NOMBRE, CAT_CL_LAT, CAT_CL_LONG from kmt_info where gestion = 0 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0 and CAT_CL_LAT <> ' ' and CAT_CL_LONG <> ' ' and CAT_CL_CODIGO <> 0 and CAT_CL_CODIGO <> 1")
'		skmt.Initialize(ruta,"kmt.db", True)
		Log($"============== Resultados = ${c.RowCount}"$)
		If c.RowCount > 0 Then
			For i = 0 To c.RowCount - 1
				c.Position = i
'				Log($"|${c.GetString("CAT_CL_LONG")}|${c.GetString("CAT_CL_LAT")}|"$)
'				Log(i&"|"&c.GetString("CAT_CL_LAT")&"|")
'				LatitudRu = 0
				If c.GetString("CAT_CL_LAT") = Null Or c.GetString("CAT_CL_LAT") = "null" Or c.GetString("CAT_CL_LAT") = "NULL" _
					Or c.GetString("CAT_CL_LONG") = Null Or c.GetString("CAT_CL_LONG") = "null" Or c.GetString("CAT_CL_LONG") = "NULL" _
				 Then
					ToastMessageShow($"Tienda con coordenadas incorrectas (${c.GetString("CAT_CL_CODIGO")})"$, False)
				Else
					Log(c.GetString("CAT_CL_CODIGO")&"      "& c.GetString("CAT_CL_LAT")&", "&c.GetString("CAT_CL_LAT"))
					If c.GetString("CAT_CL_LAT") <> "" Then LatitudRu = c.GetString("CAT_CL_LAT")
					LongitudRU = 0
					If c.GetString("CAT_CL_LONG") <> "" Then LongitudRU = c.GetString("CAT_CL_LONG")
					CODIGO=c.GetString("CAT_CL_CODIGO")
					Tienda= c.GetString("CAT_CL_NOMBRE")
					MARK_AZUL = gmap.AddMarker2(LatitudRu, LongitudRU, CODIGO, gmap.HUE_BLUE)
					MARK_AZUL.Snippet = Tienda
					Log(LatitudRu & "," & LongitudRU)
				End If
			Next
		End If
		c .Close
		If MARK_AZUL.IsInitialized Then LIST_AZUL.Add(MARK_AZUL)
	End If
	'''''''----------------------------MARKER VERDE - VENTA
	If verde = 1 Or todos = 1 Then
		c2.IsInitialized
		c2=skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_NOMBRE, CAT_CL_LONG, CAT_CL_LAT from kmt_info where gestion = 2 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0 and CAT_CL_CODIGO <> 0 and CAT_CL_CODIGO <> 1 UNION select CAT_CL_CODIGO, CAT_CL_NOMBRE, CAT_CL_LONG, CAT_CL_LAT from kmt_info2 where gestion = 2 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0 and CAT_CL_CODIGO <> 0 and CAT_CL_CODIGO <> 1")
		Log($"============== Resultados = ${c2.RowCount}"$)
		For i = 0 To c2.RowCount -1
			c2.Position = i
'			Log($"|${c2.GetString("CAT_CL_LONG")}|${c2.GetString("CAT_CL_LAT")}|"$)
			If c2.GetString("CAT_CL_LAT") = Null Or c2.GetString("CAT_CL_LAT") = "null" Or c2.GetString("CAT_CL_LAT") = "NULL" _
					Or c2.GetString("CAT_CL_LONG") = Null Or c2.GetString("CAT_CL_LONG") = "null" Or c2.GetString("CAT_CL_LONG") = "NULL" _
				 Then
				ToastMessageShow($"Tienda con coordenadas incorrectas (${c.GetString("CAT_CL_CODIGO")})"$, False)
			Else
				LongitudRU = c2.GetString("CAT_CL_LONG")
				LatitudRu = c2.GetString("CAT_CL_LAT")
				CODIGO=c2.GetString("CAT_CL_CODIGO")
				Tienda= c2.GetString("CAT_CL_NOMBRE")
				MARK_VERDE = gmap.AddMarker2(LatitudRu, LongitudRU, CODIGO,gmap.HUE_GREEN)
				MARK_VERDE.Snippet = Tienda
				Log(LatitudRu & "," & LongitudRU)
			End If
		Next
	Else
		If verde = 1 Or todos = 1 Then
			c2.IsInitialized
			c2=skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_NOMBRE, CAT_CL_LONG,CAT_CL_LAT from kmt_info where gestion = 2 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0  and CAT_CL_CODIGO <> 0 and CAT_CL_CODIGO <> 1")
			Log($"============== Resultados = ${c2.RowCount}"$)
			For i = 0 To c2.RowCount -1
				c2.Position = i
'				Log($"|${c2.GetString("CAT_CL_LONG")}|${c2.GetString("CAT_CL_LAT")}|"$)
				If c2.GetString("CAT_CL_LAT") = Null Or c2.GetString("CAT_CL_LAT") = "null" Or c2.GetString("CAT_CL_LAT") = "NULL" _
					Or c2.GetString("CAT_CL_LONG") = Null Or c2.GetString("CAT_CL_LONG") = "null" Or c2.GetString("CAT_CL_LONG") = "NULL" _
				 Then
					ToastMessageShow($"Tienda con coordenadas incorrectas (${c.GetString("CAT_CL_CODIGO")})"$, False)
				Else
					LongitudRU = c2.GetString("CAT_CL_LONG")
					LatitudRu = c2.GetString("CAT_CL_LAT")
					CODIGO=c2.GetString("CAT_CL_CODIGO")
					Tienda= c2.GetString("CAT_CL_NOMBRE")
					MARK_VERDE = gmap.AddMarker2(LatitudRu, LongitudRU, CODIGO,gmap.HUE_GREEN)
					MARK_VERDE.Snippet = Tienda
					Log(LatitudRu & "," & LongitudRU)
				End If
			Next
			c2 .Close
			If MARK_VERDE.IsInitialized Then LIST_VERDE.Add(MARK_VERDE)
		End If
	End If
'	'''''''----------------------------MARKER ROJO - NO VENTA

	If rojo = 1 Or todos = 1 Then
		c3.IsInitialized
		c3=skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_NOMBRE,CAT_CL_LONG,CAT_CL_LAT from kmt_info where gestion = 3 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0 and CAT_CL_CODIGO <> 0 and CAT_CL_CODIGO <> 1")
		Log($"============== Resultados = ${c3.RowCount}"$)
		For i = 0 To c3.RowCount -1
			c3.Position = i
'			Log($"|${c3.GetString("CAT_CL_LONG")}|${c3.GetString("CAT_CL_LAT")}|"$)
			If c3.GetString("CAT_CL_LAT") = Null Or c3.GetString("CAT_CL_LAT") = "null" Or c3.GetString("CAT_CL_LAT") = "NULL" _
					Or c3.GetString("CAT_CL_LONG") = Null Or c3.GetString("CAT_CL_LONG") = "null" Or c3.GetString("CAT_CL_LONG") = "NULL" _
				 Then
				ToastMessageShow($"Tienda con coordenadas incorrectas (${c.GetString("CAT_CL_CODIGO")})"$, False)
			Else
				LongitudRU = c3.GetDouble("CAT_CL_LONG")
				LatitudRu = c3.GetDouble("CAT_CL_LAT")
				CODIGO = c3.GetString("CAT_CL_CODIGO")
				Tienda= c3.GetString("CAT_CL_NOMBRE")
				MARK_ROJO = gmap.AddMarker2(LatitudRu, LongitudRU, CODIGO, gmap.HUE_RED)
				MARK_ROJO.Snippet = Tienda
				Log(LatitudRu & "," & LongitudRU)
			End If
		Next
	Else
		If rojo = 1 Or  todos = 1  Then
			c3.IsInitialized
			c3=skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_NOMBRE,CAT_CL_LONG,CAT_CL_LAT from kmt_info where gestion = 3 and CAT_CL_LAT is not null and CAT_CL_LONG is not null and CAT_CL_LAT <> 0 and CAT_CL_LONG <> 0 and CAT_CL_CODIGO <> 0 and CAT_CL_CODIGO <> 1")
			Log($"============== Resultados = ${c3.RowCount}"$)
			For i = 0 To c3.RowCount -1
				c3.Position = i
'				Log($"|${c3.GetString("CAT_CL_LONG")}|${c3.GetString("CAT_CL_LAT")}|"$)
				If c3.GetString("CAT_CL_LAT") = Null Or c3.GetString("CAT_CL_LAT") = "null" Or c3.GetString("CAT_CL_LAT") = "NULL" _
					Or c3.GetString("CAT_CL_LONG") = Null Or c3.GetString("CAT_CL_LONG") = "null" Or c3.GetString("CAT_CL_LONG") = "NULL" _
				 Then
					ToastMessageShow($"Tienda con coordenadas incorrectas (${c.GetString("CAT_CL_CODIGO")})"$, False)
				Else
					LongitudRU = c3.GetDouble("CAT_CL_LONG")
					LatitudRu = c3.GetDouble("CAT_CL_LAT")
					CODIGO = c3.GetString("CAT_CL_CODIGO")
					Tienda= c3.GetString("CAT_CL_NOMBRE")
					MARK_ROJO = gmap.AddMarker2(LatitudRu, LongitudRU, CODIGO, gmap.HUE_RED)
					Log(LatitudRu & "," & LongitudRU)
					MARK_ROJO.Snippet = Tienda
				End If
			Next
			If MARK_ROJO.IsInitialized Then LIST_ROJO.Add(MARK_ROJO)
			c3.Close
		End If
	End If
	''------------------------------

'	MARK_CEDIS = gmap.AddMarker3("19.3961802","-99.0784293","CEDIS", LoadBitmap(File.DirAssets, "marker-azul-0.png"))
'	If  MARK_VERDE.Visible Or MARK_ROJO.Visible  Then
'		MARK_CEDIS.Remove
'	End If
	Log("Centramos camara " & LatitudRu & ", " & LongitudRU)
	Dim aa As CameraPosition
	aa.Initialize(LatitudRu, LongitudRU, 15)  ''' RECOMENDABLE CAMBIAR A 10 PARA QUE SE VEAN MAS MARCADORES
	gmap.AnimateCamera(aa)
	
	'''''---------------------- ESTO ES PARA LOS CLICK EN LAS VENTANAS D INFORMACION-----------
	Dim OnInfoWindowClickListener1 As OnInfoWindowClickListener
	OnInfoWindowClickListener1.Initialize("OnInfoWindowClickListener1")
	GoogleMapEXTRA.SetOnInfoWindowClickListener(gmap, OnInfoWindowClickListener1)

End Sub

''''--------------------------				PRUEBA CON MARKER _CLICK

Sub OnInfoWindowClickListener1_click(Marker1 As Marker)
	Log("Tooltip clicked")
	skmt.ExecNonQuery("delete from CUENTAA")
	skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?) ", Array As Object(Marker1.Title))
	c = Starter.skmt.ExecQuery("SELECT * FROM FOTOINICIAL")
	If c.RowCount = 0 Then
		p_camara.Visible = True
		InitializeCamera
		p_camara.Left = 0
		p_camara.Visible = True
		nombreFoto = "inicio"
		b_foto_inci.Text = "Foto tienda"
	Else
'		Activity.Finish
		Starter.pre_viejo = Subs.traeTotalClientepreventaparacredito
		l_venta.Text = "Presiona el boton de ""Iniciar"" para inicar la venta"
		b_inicioVenta.Enabled = True
		b_finVenta.Enabled = False
		p_transparenciaIniciaInicioFinVenta.Visible = True
	End If
'	B4XPages.ShowPage("Cliente")
End Sub

Sub ventaIniciada
	Log("Tooltip clicked")
'	skmt.ExecNonQuery("delete from CUENTAA")
'	skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?) ", Array As Object(Marker1.Title))
'	Activity.Finish
	Starter.pre_viejo = Subs.traeTotalClientepreventaparacredito
	b_inicioVenta.Enabled = False
	b_finVenta.Enabled = True
	p_transparenciaIniciaInicioFinVenta.Visible = True
End Sub

Sub GPS_LocationChanged (Parametro As Location)
	MARK_CEDIS.IsInitialized
'	Dim sp As Int
'	sp = Ceil(Parametro.Speed * 3.6)
'	boton1.Text = sp &" "&"km/h"
'	Latitud = Parametro.Latitude
'	Longitud = Parametro.Longitude
'	p2.Initialize2(Latitud,Longitud)
'	p1.Initialize2(Lat2, Lon2)
'	Distance  = p1.DistanceTo(p2)
'	If Latitud <> 0 And Longitud <> 0 Then
'		If Distance > 10 Then
'			Lat2 = Latitud
'			Lon2 = Longitud
'			Dim cp As CameraPosition
'			cp.Initialize2(Parametro.Latitude, Parametro.Longitude, gmap.CameraPosition.Zoom, Parametro.Bearing, 0)
'			gmap.AnimateCamera(cp)
'		End If
'	End If
End Sub

Sub Activity_Pause (UserClosed As Boolean)
	GPS.Stop
End Sub

Sub B_TODOS_Click
	todos  =1
	verde = 0
	azul = 0
	rojo = 0
	gmap.Clear
	MapFragment1_Ready
End Sub

Sub B_VERDE_Click
	verde = 1
	azul = 0
	rojo = 0
	todos = 0
	gmap.Clear
	MapFragment1_Ready
End Sub

Sub B_ROJO_Click
	rojo = 1
	verde = 0
	azul = 0
	todos = 0
	gmap.Clear
	MapFragment1_Ready
End Sub

Sub B_AZUL_Click
	azul = 1
	verde = 0
	rojo = 0
	todos = 0
	gmap.Clear
	MapFragment1_Ready
End Sub

Private Sub b_inicioVenta_Click
	b_inicioVenta.Enabled = False
	et_guardarPeso.Text = ""
	r_opcion1.Checked = True
	r_opcion2.Checked = False
	r_opcion3.Checked = False
	r_opcion4.Checked = False
	b_finVenta.Enabled = True
	Subs.bitacora(Subs.fechanormal(DateTime.Now), Subs.traeUsuarioDeBD, Subs.traeAlmacen, Subs.traeRuta, "Inicia Venta", Subs.traeCliente, Subs.fechanormal(DateTime.Now), "", Starter.lat_gps, Starter.lon_gps, "2", "", "", "")
	Starter.enVenta = True
	Subs.enVenta(1, "MAPA")
	l_venta.Text = "Ve a tu app de venta y cuando termines regresa aqui y presiona el botón para ingresar ""Peso"" o ""No Venta"""
	LogColor($">>>>>> INICIA VENTA: ${Starter.enVenta} - ${Subs.traeCliente}"$, Colors.red)
End Sub

Private Sub b_finVenta_Click
	p_guardarPeso.Visible = True
'	b_inicioVenta.Enabled = True
'	b_finVenta.Enabled = False
End Sub

Private Sub p_transparenciaIniciaInicioFinVenta_Click
	Log("Fondo clicked")
	If b_finVenta.Enabled = False Then
		p_transparenciaIniciaInicioFinVenta.Visible = False
	Else
		ToastMessageShow($"Es necesario presionar "Terminar" para poder continuar"$, True)
	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)
		If p_transparenciaIniciaInicioFinVenta.Visible = True Then
			If b_finVenta.Enabled = False Then
				p_transparenciaIniciaInicioFinVenta.Visible = False
			Else
				ToastMessageShow($"Es necesario presionar "Terminar" para poder continuar"$, True)
			End If
			Return True ' Ya no hace nada aparte de ocultar el panel.
		End If
	Else
		Return False
	End If
	' Returning False signals the system to handle the key
'	Return True
End Sub

Private Sub b_guardarPeso_Click
	If et_guardarPeso.Text <> "" And et_guardarPeso.Text <> "0" And IsNumber(et_guardarPeso.Text) Then
		Private peso As Double = et_guardarPeso.Text
		et_guardarPeso.Text = peso
		
		Subs.guardaPeso("VENTA", Subs.traeAlmacen, Subs.traeRuta2(Subs.traeCliente), Subs.traeUsuarioDeBD, Subs.traeCliente, peso, "", "", "")
		Subs.bitacora(Subs.fechanormal(DateTime.Now), Subs.traeUsuarioDeBD, Subs.traeAlmacen, Subs.traeRuta, "Termina Venta", Subs.traeCliente, "", Subs.fechanormal(DateTime.Now), Starter.lat_gps, Starter.lon_gps, 2, "", "", $"Venta:${et_guardarPeso.text}"$)
		Starter.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2 where CAT_CL_CODIGO In (select cuenta from cuentaa)")
		Starter.enVenta = False
		Subs.enVenta(0, "")
		
		p_guardarPeso.Visible = False
		p_transparenciaIniciaInicioFinVenta.Visible = False
		b_inicioVenta.Enabled = True
		b_finVenta.Enabled = False
	End If
	gmap.Clear
	todos = 1
	MapFragment1_Ready
End Sub

Private Sub p_guardarPeso_Click
	
End Sub

Private Sub et_guardarPeso_TextChanged (Old As String, New As String)
	If Old <> New And IsNumber(New.trim) And New.trim <> "0" Then
		b_guardarPeso.Enabled = True
	Else
		b_guardarPeso.Enabled = False
	End If
End Sub

Private Sub b_noVenta_Click
	Log("No Venta")
	p_noVenta.Visible = True
	r_opcion1.Checked = True
	r_opcion2.Checked = False
	r_opcion3.Checked = False
	r_opcion4.Checked = False
	et_comentarioNoVenta.Text = ""
End Sub

Private Sub b_guardaNoVenta_Click
	If r_opcion1.Checked Then
		motivo = "CERRADO"
	Else If r_opcion2.Checked Then
		motivo = "NO COMPRA"
	Else If r_opcion3.Checked Then
		motivo = "CON PRODUCTO"
	Else If r_opcion4.Checked Then
		motivo = "NO ESTA EL ENCARGADO"
	Else
		motivo = "CANCELACION"
	End If
	If motivo = "CERRADO" And fotoCerrado = "" Then
		nombreFoto = Subs.traeCliente & "_cerrado"
		p_camara.Visible = True
		InitializeCamera
		p_camara.Left = 0
		p_camara.Visible = True
		p_camara.BringToFront
		b_foto_inci.Text = "Foto tienda"
	Else
		DateTime.DateFormat="yy-MM-dd HH:mm:ss"
		Dim fecha As String=DateTime.Date(DateTime.Now)
		Subs.guardaPeso("NO VENTA", Subs.traeAlmacen, Subs.traeRuta2(Subs.traeCliente), Subs.traeUsuarioDeBD, Subs.traeCliente, "0", motivo, et_comentarioNoVenta.text, fotoCerrado)
		Subs.bitacora(Subs.fechanormal(DateTime.Now), Subs.traeUsuarioDeBD, Subs.traeAlmacen, Subs.traeRuta, "No Venta", Subs.traeCliente, "", Subs.fechanormal(DateTime.Now), Starter.lat_gps, Starter.lon_gps, 2, motivo, et_comentarioNoVenta.text, $"Venta:${et_guardarPeso.text}"$)
		Starter.enVenta = False
		Subs.enVenta(0, "")
		Starter.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 3  where CAT_CL_CODIGO In (select cuenta from cuentaa)")
		p_noVenta.Visible = False
		p_guardarPeso.Visible = False
		p_transparenciaIniciaInicioFinVenta.Visible = False
		gmap.Clear
		todos = 1
		MapFragment1_Ready
	End If
End Sub

Private Sub b_cancelaNoVenta_Click
	p_noVenta.Visible = False
End Sub

Private Sub p_inicioFinVenta_Click
	
End Sub

Private Sub b_foto_inci_Click
	camEx.TakePicture
End Sub

Private Sub InitializeCamera
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_CAMERA)
'	Wait For B4XPage_PermissionResult (Permission As String, resulta As Boolean)
'	If resulta Then
		camEx.Initialize(p_cam, frontCamera, Me, "Camera1")
		frontCamera = camEx.Front
'	Else
'		ToastMessageShow("Sin permisos de camara!!!", True)
'	End If
End Sub

Sub Camera1_Ready (Success As Boolean)
	If Success Then
		camEx.SetJpegQuality(90)
		camEx.SetContinuousAutoFocus
		camEx.CommitParameters
		camEx.StartPreview
		Log(camEx.GetPreviewSize)
	Else
		ToastMessageShow("Cannot open camera.", True)
	End If
End Sub

Sub Camera1_PictureTaken (Data() As Byte)
	If b_foto_inci.Text = "Foto tienda" Then
		DateTime.DateFormat="ddMMyyyyHHmmss"
		fototomada = DateTime.Now & $"_${nombreFoto}.jpg"$
		Dim filename As String = fototomada
		Dim dir As String = File.DirInternal
		camEx.SavePictureToFile(Data, dir, filename)
		camEx.StartPreview 'restart preview
		ToastMessageShow("Picture saved." & CRLF  & "File size: " & File.Size(dir, filename), True)
		Dim Dirp As String = File.DirInternal
		Dim dir As String
		Dim Dir2 As String
		Try
			File.MakeDir(Dirp,"/adm")
			dir = "/adm"
			Log("creado en promotoria " & Dirp & dir)
		Catch
			dir = ""
			Log("creado en raiz")
		End Try
		Try
			File.MakeDir(Dirp & dir,"/reduccion")
			Dir2 = "/reduccion"
			Log("creado en promotoria " & Dirp & dir & Dir2)
		Catch
			Dir2 = ""
			Log("creado en raiz")
		End Try
		DateTime.DateFormat = "MM/dd/yyyy"
		DateTime.TimeFormat = "HH:mm:ss"
		sDate = DateTime.Date(DateTime.Now)
		sTime = DateTime.Time(DateTime.Now)
		camEx.SavePictureToFile(Data, Dirp&dir, filename)
		camEx.StartPreview 'restart preview
		ToastMessageShow("Picture saved." & CRLF  & "File size: " & File.Size(dir, filename) & dir &"," & filename, True)
		Log("Picture saved." & CRLF  & "File size: " & File.Size(dir, filename) & dir &"," & filename)
		
		Dim img As B4XBitmap = xui.LoadBitmapResize(File.DirInternal & dir, filename, 450, 600, True)
		Dim out As OutputStream = File.OpenOutput(File.DirInternal & dir & Dir2, filename, False)
		img.WriteToStream(out, 100, "PNG")
		out.Close
		If nombreFoto = "inicio" Then
			Starter.skmt.ExecNonQuery2("INSERT INTO FOTOINICIAL (RUTAA, ALMACEN, LATITUD, LONGITUD, FECHAHORA, FOTO, USUARIO) VALUES (?,?,?,?,?,?,?)",Array As Object(Subs.traeRuta, Subs.traeAlmacen, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, sDate & " " & sTime, File.ReadBytes(File.DirInternal & dir & Dir2, fototomada), Subs.traeUsuarioDeBD))
			b_foto_inci.Text = "Foto usuario"
			ChangeCamera_Click
		Else
			fotoCerrado = fototomada
			p_camara.Visible = False
			StopCamera
		End If
	Else If b_foto_inci.Text = "Foto usuario" Then
		DateTime.DateFormat="ddMMyyyyHHmmss"
		fototomada = fototomada = DateTime.Now & $"_${nombreFoto}.jpg"$
		Dim filename As String = fototomada
		Dim dir As String = File.DirInternal
		camEx.SavePictureToFile(Data, dir, filename)
		camEx.StartPreview 'restart preview
		ToastMessageShow("Picture saved." & CRLF  & "File size: " & File.Size(dir, filename), True)
		Dim Dirp As String = File.DirInternal
		Dim dir As String
		Dim Dir2 As String
		Try
			File.MakeDir(Dirp,"/adm")
			dir = "/adm"
			Log("creado en promotoria " & Dirp & dir)
		Catch
			dir = ""
			Log("creado en raiz")
		End Try
		Try
			File.MakeDir(Dirp & dir,"/reduccion")
			Dir2 = "/reduccion"
			Log("creado en promotoria " & Dirp & dir & Dir2)
		Catch
			dir = ""
			Log("creado en raiz")
		End Try
		DateTime.DateFormat = "MM/dd/yyyy"
		DateTime.TimeFormat = "HH:mm:ss"
		sDate = DateTime.Date(DateTime.Now)
		sTime = DateTime.Time(DateTime.Now)
		camEx.SavePictureToFile(Data, Dirp&dir, filename)
		camEx.StartPreview 'restart preview
		ToastMessageShow("Picture saved." & CRLF  & "File size: " & File.Size(dir, filename) & dir &"," & filename, True)
		Log("Picture saved." & CRLF  & "File size: " & File.Size(dir, filename) & dir &"," & filename)
		Dim img As B4XBitmap = xui.LoadBitmapResize(File.DirInternal & dir, filename, 450, 600, True)
		Dim out As OutputStream = File.OpenOutput(File.DirInternal & dir & Dir2, filename, False)
		img.WriteToStream(out, 100, "PNG")
		out.Close
		B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE FOTOINICIAL set FOTO2 = ? where USUARIO = ? and RUTAA = ? and ALMACEN = ? ", Array As Object (File.ReadBytes(File.DirInternal & dir & Dir2, fototomada), Subs.traeUsuarioDeBD,Subs.traeRuta, Subs.traeAlmacen ))
		b_foto_inci.Text = "Foto tienda"
		ChangeCamera_Click
		p_camara.Visible = False
		StopCamera
		If Subs.traeCliente = "0" Then
			B4XPages.MainPage.tipo_venta = "ABORDO"
		Else If Subs.traeCliente = "1" Then
			B4XPages.MainPage.tipo_venta = "RECARGA"
		Else
			B4XPages.MainPage.tipo_venta = "PREVENTA"
		End If
'		B4XPages.ShowPage("productos")
'		p_transparentePidePeso.Visible = True
	End If
End Sub

Sub ChangeCamera_Click
	camEx.Release
	frontCamera = Not(frontCamera)
	InitializeCamera
End Sub

Private Sub StopCamera
'	Capturing = False
	If camEx.IsInitialized Then
		camEx.Release
	End If
End Sub

Private Sub p_camara_Click
	
End Sub