B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=12.2
@EndOfDesignText@
Sub Class_Globals
	Private Root As B4XView 'ignore
	Private xui As XUI 'ignore
	Dim skmt, rkmt As SQL
	Private EventName As String 'ignore
	Private CallBack As Object 'ignore
	Dim rp As RuntimePermissions
	Dim safePath As String
	Dim fechaHoy As String
	Dim skmtAttached As Boolean = False
	'#######  MES Vars  ######
	Private ion As Object
'	Dim device As Phone
'	Private mesCallback As Object
'	Private mesEventName As String
	Dim RD_Init_IsInitialized As Boolean = False
	Dim btAdmin As BluetoothAdmin
	Private khdb As SQL
End Sub

'Inicializa la clase "kms_helperSubs".
Public Sub Initialize (vCallback As Object, vEventName As String, db As SQL) As Object
	EventName = vEventName
	CallBack = vCallback
	khdb = db
	Return Me
End Sub

'This event will be called once, before the page becomes visible.
'Private Sub B4XPage_Created (Root1 As B4XView)
'	Root = Root1
'	'load the layout to Root
'End Sub

'RD - Inicializa Respaldo Diario
Sub RD_Init
	Dim Dirp As String = File.DirRootExternal
	Dim Dir As String
'	Dim Dir2 As String
	Try
		File.MakeDir(Dirp,"/kmts")
		Dir = "/kmts"
'		Log("creado en kmts " & Dirp & Dir)
	Catch
		Dir = ""
'		Log("creado en raiz")
	End Try
	safePath = Dirp & Dir
	If Starter.Logger Then Log($"Safepath:${safePath}"$)
	Private name() As String = Regex.split(" ", Application.LabelName)
	rkmt.Initialize(safePath,$"${name(0)}.rkmt.km"$, True)
	skmt.Initialize(File.DirInternal,"kmt.db", False)
	If chkIfTableExists(skmt, "PEDIDO") Then rkmt.ExecNonQuery($"create table if not exists PEDIDO (${getTableColumnList(skmt, "PEDIDO")}, FECHA TEXT)"$)
	If chkIfTableExists(skmt, "CAT_DETALLES_PAQ") Then rkmt.ExecNonQuery($"create table if not exists CAT_DETALLES_PAQ (${getTableColumnList(skmt, "CAT_DETALLES_PAQ")}, FECHA TEXT)"$)
	If chkIfTableExists(skmt, "CAT_GUNAPROD") Then rkmt.ExecNonQuery($"create table if not exists CAT_GUNAPROD (${getTableColumnList(skmt, "CAT_GUNAPROD")}, FECHA TEXT)"$)
	If chkIfTableExists(skmt, "CAT_GUNAPROD2") Then rkmt.ExecNonQuery($"create table if not exists CAT_GUNAPROD2 (${getTableColumnList(skmt, "CAT_GUNAPROD2")}, FECHA TEXT)"$)
	If chkIfTableExists(skmt, "kmt_info") Then rkmt.ExecNonQuery($"create table if not exists kmt_info (${getTableColumnList(skmt, "kmt_info")}, FECHA TEXT)"$)
	DateTime.DateFormat = "MM/dd/yyyy"
	fechaHoy = DateTime.Date(DateTime.Now)
	If Starter.Logger Then Log("RKMTS: " & rkmt.IsInitialized)
	If revisaSkmtAttached And rkmt.IsInitialized Then RD_Init_IsInitialized = True Else RD_Init_IsInitialized = False
End Sub

'RD - Revisa si esta montada "kmt.db" como "skmt1" y si no, la monta
'Para que "rkmt" vea a "skmt", es necesario montarla (attach). 
Sub revisaSkmtAttached As Boolean
	skmtAttached = False
	Dim rs As ResultSet = rkmt.ExecQuery("SELECT * FROM pragma_database_list")
	Do While rs.NextRow 'Revisamos si esta montada "kmt.db" como "skmt1" y si no, la montamos.
		If rs.GetString("name") = "skmt1" Then skmtAttached = True
	Loop
	If Not(skmtAttached) Then
		rkmt.ExecNonQuery($"attach database '${File.Combine(File.DirInternal, "kmt.db")}' as skmt1;"$)
		skmtAttached = True
	End If
	Return skmtAttached
End Sub

'Inicializa la BD con "kmt.db" en "File.DirInternal", si el archivo no existe, lo copia desde "File.DirAssets".
'Ej: dim skmt as sql = dbInit
Sub dbInit As SQL 'ignore
	Private db As SQL
	If File.Exists(File.DirInternal, "kmt.db") = False Then File.Copy(File.DirAssets, "kmt.db", File.DirInternal, "kmt.db")
	db.Initialize(File.DirInternal,"kmt.db", True)
'	dbOk(True)
'	Log(db.IsInitialized)
	Return db
End Sub

'RD - Copia la tabla PEDIDO a rkmt.db en la tarjeta del celular.
Sub RD_respalda_pedido
	Private inicio As String = DateTime.Now
'	Log("Copiando PEDIDO ...")
	Private lasCols As String = getTableColumnListName(skmt, "PEDIDO")
	rkmt.BeginTransaction
	rkmt.ExecNonQuery($"delete from PEDIDO where FECHA = '${fechaHoy}'"$)
	rkmt.ExecNonQuery($"insert into PEDIDO (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.PEDIDO where substr(pe_fecha, 1, 10) = '${fechaHoy}'"$)
	rkmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
	rkmt.EndTransaction
	Log(((DateTime.Now - inicio)/1000) & " segs")
End Sub

'RD - Copia la tabla CAT_GUNAPRODS a rkmt.db en la tarjeta del celular.
Sub RD_respalda_cat_gunaprod
	Private inicio As String = DateTime.Now
'	Log("Copiando CAT_GUNAPROD ...")
	Private lasCols As String = getTableColumnListName(skmt, "CAT_GUNAPROD")
	lasCols = lasCols.Replace(", CAT_GP_IMG", "") 'Quitamos la imagen del respaldo.
	rkmt.BeginTransaction
	rkmt.ExecNonQuery($"delete from CAT_GUNAPROD where FECHA = '${fechaHoy}'"$)
	rkmt.ExecNonQuery($"insert into CAT_GUNAPROD (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.CAT_GUNAPROD"$)
	rkmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
	rkmt.EndTransaction
	Log(((DateTime.Now - inicio)/1000) & " segs")
End Sub

'RD - Copia la tabla CAT_GUNAPROD2 a rkmt.db en la tarjeta del celular.
Sub RD_respalda_cat_gunaprod2
	Private inicio As String = DateTime.Now
'	Log("Copiando CAT_GUNAPROD2 ...")
	Private lasCols As String = getTableColumnListName(skmt, "CAT_GUNAPROD2")
	lasCols = lasCols.Replace(", CAT_GP_IMG", "") 'Quitamos la imagen del respaldo.
	rkmt.BeginTransaction
	rkmt.ExecNonQuery($"delete from CAT_GUNAPROD2 where FECHA = '${fechaHoy}'"$)
	rkmt.ExecNonQuery($"insert into CAT_GUNAPROD2 (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.CAT_GUNAPROD2"$)
	rkmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
	rkmt.EndTransaction
	Log(((DateTime.Now - inicio)/1000) & " segs")
End Sub

'RD - Copia la tabla CAT_DETALLE_PAQ a rkmt.db en la tarjeta del celular.
Sub RD_respalda_cat_detalle_paq
	Private inicio As String = DateTime.Now
'	Log("Copiando CAT_DETALLES_PAQ ...")
	Private lasCols As String = getTableColumnListName(skmt, "CAT_DETALLES_PAQ")
	If rkmt.IsInitialized Then
		rkmt.BeginTransaction
		rkmt.ExecNonQuery($"delete from CAT_DETALLES_PAQ where fecha = '${fechaHoy}'"$)
		rkmt.ExecNonQuery($"insert into CAT_DETALLES_PAQ (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.CAT_DETALLES_PAQ"$)
		rkmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
		rkmt.EndTransaction
		Log(((DateTime.Now - inicio)/1000) & " segs")
	End If
End Sub

'RD - Copia la tabla CAT_DETALLE_PAQ a rkmt.db en la tarjeta del celular.
Sub RD_respalda_kmt_info
	Private inicio As String = DateTime.Now
'	Log("Copiando kmt_info ...")
	Private lasCols As String = getTableColumnListName(skmt, "kmt_info")
	rkmt.BeginTransaction
	rkmt.ExecNonQuery($"delete from kmt_info where fecha = '${fechaHoy}'"$)
	rkmt.ExecNonQuery($"insert into kmt_info (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.kmt_info"$)
	rkmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
	rkmt.EndTransaction
	Log(((DateTime.Now - inicio)/1000) & " segs")
End Sub

'RD - Realiza un "vacuum" de la base de datos "rkmt".
Sub RD_vacuum 'ignore
	Log("Vacuum")
	rkmt.ExecNonQuery("vacuum;")
End Sub

'Agrega una columna a la tabla especificada.
'Hay que indicar el "tipo"  de la columna (TEXT, INTEGER, ETC)
'Ej. agregaColumna(DB, "TABLA", "COLUMNA", "TIPO")
Sub agregaColumna(db As SQL, tabla As String, columna As String, tipo As String) 'ignore
	Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna en la tabla
		Private c As Cursor = db.ExecQuery($"SELECT COUNT(*) AS fCol FROM pragma_table_info('${tabla}') WHERE name='${columna}'"$)
		c.Position = 0
		If c.GetString("fCol") = 0 Then 'Si no esta la columna la agregamos
			db.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$)
			Log($"Columna "${columna} ${tipo}", agregada a "${tabla}"."$)
		End If
	Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch
		Try
			db.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$)
			Log($"Columna "${columna} ${tipo}", agregada a "${tabla}".."$)
		Catch
			Log(LastException)
		End Try
	End Try
End Sub

'Regresa los nombres y tipos de las columnas de una tabla dada.
Sub getTableColumnList(db As SQL, table As String) As String 'ignore
	Private l As String = ""
	If chkIfTableExists(db, table) Then
		Private c As Cursor = db.ExecQuery($"pragma table_info(${table})"$)
		If c.RowCount > 0 Then
			For i = 0 To c.RowCount - 1
				c.Position = i
				If l.Length = 0 Then
					l = $"${c.GetString("name")} ${c.GetString("type")}"$
				Else
					l = $"${l}, ${c.GetString("name")} ${c.GetString("type")}"$
				End If
			Next
		End If
	Else
		Return "No existe la tabla."
	End If
	c.Close
	Return l
End Sub

'Regresa solo los nombres de las columnas de una tabla dada.
Sub getTableColumnListName(db As SQL, table As String) As String 'ignore
	Private l As String = ""
	If chkIfTableExists(db, table) Then
		Private c As Cursor = db.ExecQuery($"pragma table_info(${table})"$)
		If c.RowCount > 0 Then
			For i = 0 To c.RowCount - 1
				c.Position = i
				If l.Length = 0 Then
					l = $"${c.GetString("name")}"$
				Else
					l = $"${l}, ${c.GetString("name")}"$
				End If
			Next
		End If
	Else
		Return "No existe la tabla."
	End If
	c.Close
	Return l
End Sub

'Revisa si una tabla dada existe en una base de datos dada, regresa true o false.
Sub chkIfTableExists(db As SQL, table As String) As Boolean 'ignore
	Private t As Boolean = False 'ignore
	If db.IsInitialized Then
		Private c As Cursor = db.ExecQuery($"SELECT name FROM sqlite_master WHERE type='table' AND name='${table}'"$)
		If c.RowCount > 0 Then t = True
		c.Close
	End If
	Return t
End Sub

'Hace visible y trae al frente el panel con los parametros "Top" y "Left" dados
Sub panelVisible(panel As Panel, top As Int, left As Int) 'ignore
	panel.BringToFront
	panel.Visible = True
	panel.Top = top
	panel.Left = left
End Sub

'Centra una etiqueta dentro de un elemento superior
Sub centraEtiqueta(elemento As Label, anchoElementoSuperior As Int) 'ignore
	elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2)
	etiquetaCentrada(True)
End Sub

Sub etiquetaCentrada(Success As Boolean)
	If SubExists(CallBack, EventName & "_etiquetaCentrada") Then
		CallSub2(CallBack, EventName & "_etiquetaCentrada", Success)
	End If
End Sub

'Centra un panel horizontalmente dentro de un elemento superior
Sub centraPanel(elemento As Panel, anchoElementoSuperior As Int) 'ignore
	elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2)
End Sub

'Centra un panel verticalmente dentro de un elemento superior
Sub centraPanelV(elemento As Panel, altoElementoSuperior As Int) 'ignore
	elemento.Top = Round(altoElementoSuperior/2)-(elemento.Height/2)
End Sub

'Centra una barra de progreso dentro de un elemento superior
Sub centraProgressBar(elemento As ProgressBar, anchoElementoSuperior As Int) 'ignore
	elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2)
End Sub

'Regresa el usuario de la tabla USUARIOA, si no lo encuentra regresa "SinUsuario"
Sub traeUsuarioDeDB As String 'ignore
	Private c As Cursor
	Private u As String = "SinUsuario"
	c = khdb.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	If c.RowCount > 0 Then u = c.GetString("USUARIO")
	c.Close
	Return u
End Sub

'Regresa el almacen actual de la base de datos.
Sub traeAlmacen As String 'ignore
	Private c As Cursor
	Private a As String
	c = khdb.ExecQuery("select  ID_ALMACEN from CAT_ALMACEN")
	c.Position = 0
	a = c.GetString("ID_ALMACEN")
	c.Close
	Return a
End Sub

'Regresa el nombre del producto desde CAT_GUNAPROD.
Sub traeProdNombre(id As String) As String 'ignore
	Private h As Cursor
	Private n As String
	h = khdb.ExecQuery2("select CAT_GP_NOMBRE from CAT_GUNAPROD where CAT_GP_ID = ? ", Array As String(id.Trim))
	If h.RowCount > 0 Then
		h.Position = 0
		n = h.GetString("CAT_GP_NOMBRE")
'		Log(h.RowCount&"|"&id&"|"&n&"|")
	End If
	h.Close
	If n = Null Or n="" Then n = "N/A"
'	Log(h.RowCount&"|"&id&"|"&n&"|")
	Return n
End Sub

'Regresa la ruta actual de la base de datos.
Sub traeRuta As String 'ignore
	Private c As Cursor
	Private r As String
	c = khdb.ExecQuery("select CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
	r = "0"
	If c.RowCount > 0 Then
		c.Position=0
		r = c.GetString("CAT_CL_RUTA")
	End If
	c.Close
	Return r
End Sub

'Regresa el cliente actual de la base de dtos (CUENTAA).
Sub traeCliente As String 'ignore
	Private c As Cursor
	Private cl As String
	c = khdb.ExecQuery("Select CUENTA from cuentaa")
	c.Position=0
	cl = c.GetString("CUENTA")
	c.Close
	Return cl
End Sub

'Regresa en un mapa el total de productos y monto del pedido del cliente actual
'resultado = {"productos":"antidad_de_productos", "monto":"costo_total"}
Sub traeTotalesClienteActual As Map 'ignore
	Private m As Map
	m.Initialize
	Private c_prodsX As Cursor = khdb.ExecQuery("select ifnull(sum(PE_CANT), 0) as cantProds, ifnull(sum(PE_COSTO_TOT), 0) as costoTotal FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) order by PE_PRONOMBRE asc")
	c_prodsX.Position = 0
'	LogColor($"Productos de la orden: ${c_prodsX.GetString("cantProds")}, Total: ${c_prodsX.GetString("costoTotal")}"$, Colors.red)
	m = CreateMap("productos": c_prodsX.GetString("cantProds"), "monto" : c_prodsX.GetString("costoTotal"))
	Return m
End Sub

'Borra el pedido del cliente actual.
'Borra los registros de la tabla "PEDIDO" y "PEDIDO_CLIENTE"
'Actualiza las tablas "cat_gunaprod" y "kmt_info".
Sub borraPedidoClienteActual As String 'ignore
	Private thisC As Cursor
	thisC = khdb.ExecQuery("select PE_PROID,PE_CANT FROM PEDIDO where pe_cliente in (Select CUENTA from cuentaa) ")
	If thisC.RowCount>0 Then
		For i=0 To thisC.RowCount -1
			thisC.Position=i
			khdb.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen + ? where cat_gp_id = ?", Array As Object(thisC.GetString("PE_CANT"),thisC.GetString("PE_PROID")))
			khdb.ExecNonQuery2("INSERT INTO INVENT_X_ENVIAR (ALMACEN , PROID , CANTIDAD ) VALUES(?,?,?) ", Array As Object (traeAlmacen, thisC.GetString("PE_PROID"),thisC.GetString("PE_CANT")* -1))
		Next
	End If
	khdb.ExecNonQuery("delete from pedido_cliente where pc_cliente in (Select CUENTA from cuentaa)")
	khdb.ExecNonQuery("delete from pedido where pe_cliente in (Select CUENTA from cuentaa)")
	khdb.ExecNonQuery("UPDATE kmt_info set gestion = 0  where CAT_CL_CODIGO In (select cuenta from cuentaa)")
	Return 1
End Sub

'Regresa verdadero si la columna gestion en la tabla "kmt_info" tene valor 2.
'si no, entonces regresa falso.
Sub pedidoGuardado As Boolean 'ignore
	Private guardado As Boolean = False
	Private g As Cursor = khdb.ExecQuery("select gestion from kmt_info where CAT_CL_CODIGO in (Select CUENTA from cuentaa)")
	If g.RowCount > 0 Then
		g.Position=0
		If g.GetString("gestion") = "2" Then guardado = True
	End If
	Log($"Guardado=${guardado}"$)
	Return guardado
End Sub

'Regresa verdadero si hay pedido en la tabla "PEDIDO" del cliente actual.
Sub hayPedido As Boolean 'ignore
	Private thisC As Cursor = khdb.ExecQuery($"select count(PE_CLIENTE) as hayPedido from PEDIDO where PE_CLIENTE = '${traeCliente}'"$)
	thisC.Position = 0
	Private hay As Boolean = False
	If thisC.GetInt("hayPedido") > 0 Then hay = True
'	Log($"Cliente actual=${traeCliente}, hayPedido=${hay}"$)
	Return hay
End Sub

'Regresa verdadero si el usuario actual ya imprimio su venta
Sub revisaImpresa As Boolean
	Dim imp As Boolean = False
	Dim i As Cursor = khdb.ExecQuery("select count(*) as CUANTOS from kmt_info where (impresion = 1 or cat_cl_codigo in (select ci_cuenta from cliente_impreso)) and CAT_CL_CODIGO in (Select CUENTA from cuentaa)")
	i.Position = 0
	If i.GetString("CUANTOS") > 0 Then imp = True Else imp = False
	Return imp
End Sub

'Guarda el nombre y version de la app en CAT_VARIABLES.
Sub guardaAppInfo 'ignore
	khdb.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'EMPRESA' or CAT_VA_DESCRIPCION = 'APP_NAME' or CAT_VA_DESCRIPCION = 'APP_VERSION'")
	khdb.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('APP_NAME', '${Application.LabelName}')"$)
	khdb.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('APP_VERSION', '${Application.VersionName}')"$)
End Sub

'Regresa el Id del producto con el nombre dado y el tipo de venta dado.
Sub traeProdIdConNombre(n As String, tipoVenta As String) As String
	Private elId As String = "N/A"
	Private n0 As Cursor = khdb.ExecQuery($"select CAT_GP_ID from ${traeTablaProds(tipoVenta)} where CAT_GP_NOMBRE = '${n}'"$)
	If n0.RowCount > 0 Then
		n0.Position = 0
		elId = n0.GetString("CAT_GP_ID")
	End If
	Return elId
End Sub

'Regresa la tabla de productos (cat_gunaprod o cat_gunaprod2) dependiendo del tipo de venta.
Sub traeTablaProds(tipoventa As String) As String 'ignore
	Private tablaProds As String = "cat_gunaprod2"
	If tipoventa = "ABORDO" Or tipoventa = "PREVENTA" Then tablaProds = "cat_gunaprod"
'	LogColor($"Tipo= ${tipoventa}, tabla=${tablaProds}"$, Colors.RGB(200,136,0))
	Return tablaProds
End Sub

'Muestra en el Log los campos y valores que regresan en el JobDone.
Sub logJobDoneResultados(resultado As DBResult) 'ignore
	For Each records() As Object In resultado.Rows
		LogColor($"====== ${resultado.Tag} - REGISTROS = ${resultado.Rows.Size}"$, Colors.RGB(215,37,0))
		For Each k As String In resultado.Columns.Keys
			LogColor(k & " = " & records(resultado.Columns.Get(k)), Colors.RGB(215,37,0))
		Next
	Next
End Sub

'Revisa si la aplicación tiene permiso para acceder a las notificaciones.
Sub CheckNotificationAccess As Boolean
	Dim ph As Phone
	Dim nstr, pstr As String
	Dim r As Reflector
	pstr = r.GetStaticField("anywheresoftware.b4a.BA", "packageName")
	nstr = ph.GetSettings("enabled_notification_listeners")
	Return nstr.Contains(pstr)
End Sub

'################  Manage External Storage (MES)   #########################
'
''Inicializa "Manage External Storage" (MES), que nos da acceso a la tarjeta de memoria en Android 11+
'Public Sub MES_Init (mCallBack As Object, mEventName As String)
'	mesCallback = mCallBack
'	mesEventName = mEventName
'End Sub
'
'Sub MES_checkPermission 'ignore
''	' 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.CheckAndRequestPermission(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(MES_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")
''			MES_GetPermission
''			Wait For MES_StorageAvailable
''		End If
''	End If
'End Sub
'
'' Determine if the app already has MANAGE_EXTERNAL_STORAGE call Environment.isExternalStorageManager()
'' Return True if this app already has MANAGE_EXTERNAL_STORAGE permission
'Public Sub MES_HasPermission As Boolean
'	Dim has As Boolean	
'	Dim jo As JavaObject
'	jo.InitializeStatic("android.os.Environment")
'	has = jo.RunMethod("isExternalStorageManager", Null)	
'	Return has
'End Sub
'
'' Check whether this app has MANAGE_EXTERNAL_STORAGE permission
'' If not show the user a dialog to enable MANAGE_EXTERNAL_STORAGE permission for this app
'' Raises the StorageAvailable event in the calling activity when complete
'Public Sub MES_GetPermission
'	If MES_HasPermission Then
'		RaiseEvent
'		Return
'	End If
'	Dim in As Intent
'	' Be sure to reference your app package name in "pakageg:xxx"
'	in.Initialize("android.settings.MANAGE_APP_ALL_FILES_ACCESS_PERMISSION", $"package:${Application.PackageName}"$)
'	StartActivityForResult(in)
'End Sub
'
'Private Sub RaiseEvent
'	Log("Calling : " &  mesEventName & "_StorageAvailable")
'	CallSubDelayed(mesCallback, mesEventName & "_StorageAvailable")
'End Sub
'
'Private Sub ion_Event (MethodName As String, Args() As Object) As Object
'	RaiseEvent
'	Return Null
'End Sub
'
'Private Sub StartActivityForResult(i As Intent)
'	Dim jo As JavaObject = MES_GetBA
'	ion = jo.CreateEvent("anywheresoftware.b4a.IOnActivityResult", "ion", Null)
'	jo.RunMethod("startActivityForResult", Array As Object(ion, i))
'End Sub
'
'Private Sub MES_GetBA As Object
'	Dim jo As JavaObject = Me
'	Return jo.RunMethod("getBA", Null)
'End Sub
'################  TERMINA Manage External Storage (MES)   #########################


'################  INICIA ENABLE BLUETOOTH   #########################
Sub StartBluetooth 'ignore
	btAdmin.Initialize("btAdmin")
	Log("btAdmin: " & btAdmin.IsEnabled)
	If btAdmin.IsEnabled = False Then
		Wait For (EnableBluetooth) Complete (Success As Boolean)
		If Success = False Then
			ToastMessageShow("Failed to enable bluetooth", True)
		End If
		Log(Success)
	End If
	Log($"BTADMIN: ${btAdmin.IsEnabled}"$)
End Sub

Sub EnableBluetooth As ResumableSub
	ToastMessageShow("Enabling Bluetooth adapter...", False)
	Private ph As Phone
	If ph.SdkVersion >= 31 Then
		rp.CheckAndRequest("android.permission.BLUETOOTH_CONNECT")
		Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
		If Result = False Then Return False
		Log($"BTCONNECT: ${Result}"$)
		If ph.SdkVersion >= 33 Then
			Dim in As Intent
			in.Initialize("android.bluetooth.adapter.action.REQUEST_ENABLE", "")
			StartActivityForResult(in)
			Wait For ion_Event (MethodName As String, Args() As Object)
			Return btAdmin.IsEnabled
		End If
	End If
	Return btAdmin.Enable
End Sub

Private Sub GetBA As Object
	Dim jo As JavaObject = Me
	Return jo.RunMethod("getBA", Null)
End Sub

Private Sub StartActivityForResult(i As Intent)
	Dim jo As JavaObject = GetBA
	ion = jo.CreateEvent("anywheresoftware.b4a.IOnActivityResult", "ion", Null)
	jo.RunMethod("startActivityForResult", Array As Object(ion, i))
End Sub
'################  TERMINA ENABLE BLUETOOTH   #########################