﻿B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=11.5
@EndOfDesignText@
Sub Class_Globals
	Private Root As B4XView
	Public mEventName As String 'ignore
	Public mCallBack As Object 'ignore
	'Private mBase As Panel
	
	Private xui As XUI
	Private b4xv As B4XView
	Private pnlMain As Panel
	Dim actionBar As clsActionBar
	
	Private THEME As String=""
	Private LANGUAGE As String=""
	
	Private xui As XUI 'ignore
	Public Tag As Object
	Private b4xv As B4XView
	Private globalMap As Map


	Dim actionBar As clsActionBar
	Public prevPage As String
	
	Public scanText As String=""
	Public scanTitle As String=""
	Dim lblScanText As Label
	'Private torch As Panel
	Public showAutoOpen As Boolean=False
	Public ignoreEvents As Boolean=False
	Public reqLocation As Boolean=False
	Dim pnlPreview As B4XView
	#if b4a
	'Private scan As NewQRCodeReaderView
	#end if
	#if b4i
	'Private scan As BarcodeScanner
	#End If
	
	Dim pLottie As B4XView
	#if b4a
	Private xLottie As LottieAnimationView
	#end if
	#if b4i
	Private xLottie As iLottie
	#End If	
	Dim xAutOpen As clsCheckBox

	#if B4A
	Private rp As RuntimePermissions
	Private detector As JavaObject
	Private camEx As CameraExClass
	Private LastPreview As Long
	Private IntervalBetweenPreviewsMs As Int = 100
	#else if B4i
	Private scanner As BarcodeScanner
	#End If
	Private Capturing As Boolean
	Private MyTaskIndex As Int
	Private scanTimer As Timer
End Sub

Sub B4XPage_Invisible
	If Root.IsInitialized Then
		Root.Visible=False
		Root.Color=col.clrBackground
	End If
End Sub
Sub HOME_Click
	If actionBar.BackArrow=True Then
		StopCamera
		If prevPage<>"" Then
		
			CallSub(B4XPages.GetPage(prevPage), "B4XPage_Invisible")
			xc.navigateToPage(prevPage)
		Else
			CallSub(B4XPages.MainPage, "B4XPage_Invisible")
			xc.navigateToPage("MainPage")
		End If
	End If
End Sub

Sub tmrSearch_Tick
	'do search
End Sub
Sub initStart
End Sub
'Sub delayScan
'	scan.Start
'End Sub
'Sub delayCheck(args() As Object)
'	Dim xAutOpen As clsCheckBox=args(0)
'	ignoreEvents=True
'	Sleep(1)
'	xAutOpen.Checked=args(1)
'	ignoreEvents=False
'End Sub
Sub setTorch(enable As Boolean)
	
	Main.kvs.put("torchEnabled", enable)
	b4xv=actionBar.getIcon(0)
	
	Dim clsDraw As clsDrawPanel
	clsDraw.Initialize(Me, "torch")
	If Main.kvs.Get("torchEnabled")=True Then
		b4xv.Text=Chr(0xE3E7)
		'b4xv.SetColorAnimated(300, col.clrGray, col.clrBlack)
		b4xv.TextColor=col.clrBlack
		
	Else
		b4xv.Text=Chr(0xE3E6)
		'b4xv.SetColorAnimated(300, col.clrBlack, col.clrGray)
		b4xv.TextColor=col.clrGray 'clsDraw.generate(Chr(0xE25F), xc.b4xFontM(xc.titleSize*1.5), col.clrGray)
		
	End If
	If camEx.IsInitialized Then
		If enable Then
			camEx.AutoExposureMode = "ON"
			camEx.PreviewSettingsMap.Put("FLASH_MODE", 2) 'TORCH
			camEx.StartPreview(MyTaskIndex, False)
		Else
			camEx.AutoExposureMode = "ON"
			camEx.PreviewSettingsMap.Put("FLASH_MODE", 0) 'TORCH
			camEx.StartPreview(MyTaskIndex, False)
			
		End If
	End If
End Sub
Sub TORCH_Click
	setTorch(Not(Main.kvs.Get("torchEnabled").As(Boolean)))
'	b4xv.RemoveViewFromParent
	
'	pnlMain.AddView(clsDraw.GetBase,actionBar.Width-clsDraw.Width-10dip, actionBar.Height+10dip,clsDraw.Width, clsDraw.Height)
End Sub
Sub autoOpen_CheckedChange(checked As Boolean)
	xc.Logd("ignoreEvents:" & ignoreEvents)
	If ignoreEvents=False Then
		If checked Then
			Main.kvs.put("startupScan",1)
		Else
			Main.kvs.put("startupScan",0)
		End If
	End If
End Sub
#if b4i
Sub scan_Detected (Codes As List)

	Dim results As String=""
	For Each code As BarcodeCode In Codes
		results=(code.Value)
	Next
	scan.Stop
	xc.logd(scanDone)
	'If Not(scanDone) Then
		scanDone=True
		CallSub2(Main, "playPool", "beep")
		If xui.SubExists(mCallBack, mEventName & "_ScanQR", 1) Then
			CallSub2(mCallBack, mEventName & "_ScanQR", results)
		End If
		
	'End If
	xc.navigateToPage(prevPage)
	scanDone=True
End Sub
#End If
	
#if b4a

Sub FoundPPU(retval As String)
	StopCamera
	CallSub2(Main, "playPool", "beep")
	If xui.SubExists(mCallBack, mEventName & "_ScanOCR", 1) Then
		CallSub2(mCallBack, mEventName & "_ScanOCR", retval)
	End If
		
	pLottie.Visible=False
	xc.navigateToPage(prevPage)
	Sleep(0)
End Sub
#end if
'You can add more parameters here.
Public Sub Initialize(Callback As Object, EventName As String, previousPage As String) As Object
	THEME=Main.THEME
	LANGUAGE=Main.language
	mEventName = EventName
	mCallBack = Callback
	globalMap.Initialize
	prevPage=previousPage
	B4XPages.GetManager.TransitionAnimationDuration = 0
	scanTitle=""
	scanTitle=""
	scanTimer.Initialize("scanTimer", 500)
	#if b4a	
'	scan.Initialize("scan")
'	scan.QRDecodingEnabled = True
'	scanText=""
'	scanTitle=""
'	scan.AutofocusInterval = 500
'	scan.ScanNow = False
'	scan.Visible = True
'	scan.ResultPointColor = Colors.Red
'	scan.setBackCamera
'	scan.Color=Colors.ARGB(50,0,0,0)
'	scan.TorchEnabled=Main.kvs.Get("torchEnabled")
'	scanDone=False
	#end if	
	
	Return Me
End Sub

Sub setReturnPage(pg As String)
	prevPage=pg
End Sub
Sub setText(txt As String)
	scanText=txt
	If lblScanText.IsInitialized Then
		
		lblScanText.Text=scanText
		#if b4a
		Dim su As StringUtils
		lblScanText.Height=su.MeasureMultilineTextHeight(lblScanText, lblScanText.Text)

		#end if
		#if b4i
		lblScanText.SizeToFit
		#End If		
	End If
End Sub
Sub setTitle(txt As String)
	scanTitle=txt
	If lblScanText.IsInitialized Then
		
		lblScanText.Text=scanText
		#if b4a
		Dim su As StringUtils
		lblScanText.Height=su.MeasureMultilineTextHeight(lblScanText, lblScanText.Text)
		#end if
		#if b4i
		lblScanText.SizeToFit
		#End If
	End If
End Sub
'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
	Root=Root1
	Root.Color=col.clrBackground
	Root.RemoveAllViews
	
	pnlMain=xui.CreatePanel("")
	Root.AddView(pnlMain, 0, 0, B4XPages.MainPage.RootWidth, B4XPages.MainPage.RootHeight)
	pnlMain.Tag="MENU"
	actionBar.Initialize(Me, "actionBar")
	Sleep(0)


	Dim actionIcons As List
	actionIcons.Initialize
	If Main.kvs.Get("torchEnabled")=True Then
		actionIcons.Add(CreateMap("icon": Chr(0xE3E7), "font": xc.b4xFontM(xc.bigSize), "tag":"TORCH", "color":col.clrBlack))
	Else
		actionIcons.Add(CreateMap("icon": Chr(0xE3E6), "font": xc.b4xFontM(xc.bigSize), "tag":"TORCH", "color":col.clrGray))
	End If
	actionBar.Title=scanTitle

	actionBar.Icons=actionIcons

	actionBar.BackArrow=True
	actionBar.EnableSearch=False
	actionBar.AddToParent(pnlMain)

	pnlMain.LoadLayout("pnlPreview")
	pnlPreview.SetLayoutAnimated(0, 0, actionBar.GetBase.Height, xc.width(100), xc.width(100))
	
	'Try
	'pnlScan=xui.CreatePanel("pnlScan")
		
		#if b4a
	'scan.RemoveView
	'Sleep(0)
	'pnlScan.AddView(scan, 0,0,pnlScan.Width, pnlScan.Height)
		#end if
		#if b4i
'			Dim types As List
'			types.Initialize
'			types.add(scan.TYPE_QR)
'			scan.Initialize2("scan", pnlScan, types)
'			scan.Resize
		#End If


	'Catch
	'	Log(LastException)
	'End Try
	lblScanText.Initialize("lblScanText")
	pnlMain.AddView(lblScanText, 10dip,pnlPreview.Width+pnlPreview.Top+10dip, xc.width(100)-20dip, 1dip)
	#If B4I
	'Wait For B4XPage_Resize (Width As Int, Height As Int)
	'Sleep(250)
	#End If
	
	pLottie=xui.CreatePanel("")
	pnlMain.AddView(pLottie, xc.width(35),xc.width(35)+actionBar.Height, xc.width(30), xc.width(30))
	Dim p As B4XView=xui.CreatePanel("")
	pnlMain.AddView(p, 0,actionBar.Height,xc.width(100), xc.width(20))
	p.SetColorAndBorder(col.clrBackgroundAlpha,0 ,0,0)
	
	
	Dim p2 As B4XView=xui.CreatePanel("")
	pnlMain.AddView(p2, 0,p.Top+xc.width(20),xc.width(20), xc.width(80))
	p2.SetColorAndBorder(col.clrBackgroundAlpha,0 ,0,0)
	
	Dim p2 As B4XView=xui.CreatePanel("")
	pnlMain.AddView(p2, xc.width(80),p.Top+xc.width(20),xc.width(20), xc.width(80))
	p2.SetColorAndBorder(col.clrBackgroundAlpha,0 ,0,0)
	
	Dim p As B4XView=xui.CreatePanel("")
	pnlMain.AddView(p, xc.width(20),p2.Top+p2.Height-xc.width(20),xc.width(60), xc.width(20))
	p.SetColorAndBorder(col.clrBackgroundAlpha,0 ,0,0)
	#if b4a
	pLottie.LoadLayout("xLottie")
	xLottie.setAnimationFromJson(File.ReadString(File.DirAssets, "qr.viewfinder3.json"), xc.generarClave(10))
	xLottie.RepeatCount=9999
	xLottie.PlayAnimation
	#end if
	#if b4i 
		xLottie.Initialize("xLottie", Me)
		xLottie.AnimationFromfile(File.DirAssets, "qr.viewfinder3.json")
		pLottie.AddView(xLottie.AnimationView,0,0,pLottie.Width, pLottie.Height)
		xLottie.ContentMode=xLottie.ASPECT_FIT_CONTENT
		xLottie.LoopAnimation=True
		xLottie.Play
	#End If 
	'End If
	pLottie.BringToFront
	pLottie.Visible=True
	StopCamera
		#if B4A
		CreateTextDetector2
		#Else if B4i
		scanner.Initialize2("scanner", pnlPreview, Array(scanner.TYPE_93, scanner.TYPE_128, scanner.TYPE_QR))
		Wait For Scanner_Ready (Success As Boolean)
		If Success = False Then
	'btnStartStop.Enabled = False
	'toast.Show("Failed to initialize the scanner.")
		End If
		#end if	
End Sub

Sub checkTheme	
	If THEME<>Main.THEME Or LANGUAGE<>Main.language Then
		THEME=Main.THEME
		LANGUAGE=Main.language
		B4XPage_Created(Root)
		Sleep(0)
	End If
End Sub

Private Sub B4XPage_Disappear
	enableLottie(False)
	pLottie.Visible=False
	StopCamera
End Sub
Private Sub B4XPage_Appear
	CallSub2(Main, "enableLocation", True)
	
	If THEME<>Main.THEME Or LANGUAGE<>Main.language Then
		THEME=Main.THEME
		LANGUAGE=Main.language
		B4XPage_Created(Root)
	End If
	CallSub(Main, "setNavBar")
	Root.Visible=False
		
	'If torch.IsInitialized Then
	'	b4xv=torch
	'	b4xv.RemoveViewFromParent
	'End If

	Root.Color=col.clrBackground
	'pnlMain.RemoveAllViews
	
			



	
	b4xv=lblScanText
	b4xv.Font=xc.b4xFontLight(xc.titleSize)
	b4xv.TextColor=col.clrBlack
	b4xv.Text=scanText
	
	#if b4a
	Dim su As StringUtils
	lblScanText.Height=su.MeasureMultilineTextHeight(lblScanText, lblScanText.Text)
	#end if
	#if b4i
	lblScanText.Multiline=True
	lblScanText.SizeToFit
	#End If	

	If showAutoOpen Then
		Sleep(0)
		
		xAutOpen.Initialize(Me, "autoOpen")
		xAutOpen.Title=xc.tr("TAG.STARTQR")
		xAutOpen.checkedFontChange=False
		xAutOpen.Checked=(1=Main.kvs.get("startupScan"))
		xAutOpen.Generate
		pnlMain.AddView(xAutOpen.GetBase, 0, xc.height(100)-xAutOpen.Height-20dip, xc.width(100), xAutOpen.Height)

	End If
	Sleep(0)
	xc.pdh
	Dim canContinue As Boolean=True
	If reqLocation Then
		If xc.isLocationEnable<>1 Then
				
			canContinue=False
			'CallSubDelayed2(mCallBack, "changeUse", False)
			Dim xui As XUI
			Dim Dialog As B4XDialog
			Dialog.Initialize(Root)
			Dialog=xc.createDialogLottie(Dialog)
			Dim p As Panel=xc.createDialogLottiePanel(Root, xc.tr("STATUS.DISTANCE"), "enable.location.json")
			Dim rs As ResumableSub = Dialog.ShowCustom(p, "", "", xc.tr("BTN.CONTINUE").ToUpperCase)
				
			Dim b4xv As B4XView
			b4xv=Dialog.GetButton(xui.DialogResponse_Cancel)
			b4xv.Width=Dialog.Base.Width
			b4xv.Left=0
			b4xv.SetTextAlignment("CENTER", "RIGHT")
			Wait For (rs) Complete (rx As Int)
			Sleep(0)
		#if b4a
			Dim rp As RuntimePermissions
			rp.CheckAndRequest(rp.PERMISSION_ACCESS_FINE_LOCATION)
			Wait for B4XPage_PermissionResult (Permission As String, Result As Boolean)
			canContinue=False
			If Result Then
				'canContinue=True
				B4XPages.GetManager.RaiseEvent(B4XPages.GetManager.GetTopPage, "Remote_UpdateDistances", Null)
			End If
		#end if
		#if b4i
		If xc.isLocationEnable<>1 Then
			Main.csu.CallSubDelayedPlus(Main, "askLocations", 300)
		End If
		
		#End If	
		End If
	End If
	
	If Not(canContinue) Then
		HOME_Click
	Else
		

	#if b4a
		pLottie.Visible=True
'		scan.startCamera
'		Sleep(50)
'		scan.ScanNow=True
'		scan.AutofocusInterval=500
'		scan.TorchEnabled=Main.kvs.Get("torchEnabled")
		
'		Sleep(300)
'		StartCamera
'		If Main.kvs.Get("torchEnabled").As(Boolean)=True Then
'			camEx.SetFlashMode("on")
'		Else
'			camEx.SetFlashMode("off")
'		End If

	#end if
	#if b4i
	Sleep(0)
		'Main.csu.CallSubDelayedPlus(Me, "delayScan", 300)
	scan.Start
	If Main.kvs.Get("torchEnabled")=True Then
		scan.TorchMode=scan.TORCH_ON
	Else
		scan.TorchMode=scan.TORCH_OFF 
	End If
	#End If	
		StartCamera
		enableLottie(True)
	End If
	
	Root.SetVisibleAnimated(300, True)
	
End Sub

Sub enableLottie(enable As Boolean)
	Sleep(500)
	#if b4a
	If xLottie.IsInitialized Then
		If enable Then
			xLottie.PlayAnimation
		Else
			xLottie.pauseAnimation
		End If
	End If
	#end if
	
	#if b4i 
	If xLottie.IsInitialized Then
		If enable Then 
			xLottie.Play
		Else
			xLottie.Stop
		End If
	End If
	#End If 	
End Sub
Sub btnStartStop_Click
	If Capturing = False Then
		StartCamera
	Else
		StopCamera
	End If
End Sub
Private Sub B4XPage_CloseRequest As ResumableSub
	
	If actionBar.BackArrow=True Then
		HOME_Click
		Return False
	End If
	Return False
End Sub

Private Sub StopCamera
	Capturing = False
	pnlPreview.Visible = False
	#if B4A
	If camEx.IsInitialized Then
		camEx.Stop
		'camEx.Release
	End If
	#Else If B4i
	scanner.Stop
	#end if
	scanTimer.Enabled=False
End Sub

Private Sub StartCameraShared
	pnlPreview.Visible = True
	Capturing = True
End Sub


#if B4A
Private Sub StartCamera

	StartCameraShared
	'camEx.Initialize(pnlPreview, False, Me, "Camera1")

	camEx.Initialize(pnlPreview)
	
	'camEx.OpenCamera(False)
	Wait For (camEx.OpenCamera(False)) Complete (TaskIndex As Int)
	If TaskIndex > 0 Then
		MyTaskIndex = TaskIndex 'hold this index. It will be required in later calls.
	
		
		Wait For(PrepareSurface) Complete (Success As Boolean)
		Sleep(0)
		setTorch(Main.kvs.Get("torchEnabled").As(Boolean))
	End If

	scanTimer.Enabled=True
'	Wait For Camera1_Ready (Success As Boolean)
'	If Success Then
'		Log(camEx.SupportedFocusModes)
'		'camEx.FocusMode=0
'		'camEx.SetContinuousAutoFocus
'		'camEx.CommitParameters
'		'camEx.StartPreview
'	Else
'		StopCamera
'	End If
End Sub

Sub PrepareSurface As ResumableSub
	camEx.PreviewSize.Initialize(pnlPreview.width, pnlPreview.height)
	
	Wait For (camEx.PrepareSurface(MyTaskIndex)) Complete (Success As Boolean)
	If Success Then camEx.StartPreview(MyTaskIndex, False)
	Return Success
End Sub

Private Sub CreateTextDetector2
	Dim ctxt As JavaObject
	ctxt.InitializeContext
	Dim builder As JavaObject
	builder.InitializeNewInstance("com.google.android.gms.vision.text/TextRecognizer.Builder".Replace("/", "."), Array(ctxt))
	Dim TextRecognizerClass As String = "com.google.android.gms.vision.text.TextRecognizer".Replace("/", ".")
	Dim TextRecognizerStatic As JavaObject
	TextRecognizerStatic.InitializeStatic(TextRecognizerClass)
	detector = builder.RunMethod("build", Null)
	Dim operational As Boolean = detector.RunMethod("isOperational", Null)
	Log("Is detector operational: " & operational)
End Sub

Private Sub Camera1_PreviewTaken (Image As Object)
End Sub
Sub scanTimer_Tick
	If camEx.IsInitialized Then
		'Private Sub Camera1_Preview (data() As Byte)
		If DateTime.Now > LastPreview + IntervalBetweenPreviewsMs Then
			'Dim n As Long = DateTime.Now
			Try
				Dim frameBuilder As JavaObject
				frameBuilder.InitializeNewInstance("com/google/android/gms/vision/Frame.Builder".Replace("/", "."), Null)
				frameBuilder.runmethod("setBitmap", Array( camEx.GetPreviewBitmap(pnlPreview.Width, pnlPreview.Height) ))
				Dim frame As JavaObject = frameBuilder.RunMethod("build", Null)
				Dim SparseArray As JavaObject = detector.RunMethod("detect", Array(frame))
				LastPreview = DateTime.Now
				Dim Matches As Int = SparseArray.RunMethod("size", Null)
				If Matches > 0 Then
					For i = 0 To Matches - 1
						Dim TextBlock As JavaObject = SparseArray.RunMethod("valueAt", Array(i))
						Dim PPU As String=TextBlock.RunMethod("getValue", Null)
						PPU=PPU.Trim.ToUpperCase.Replace(" ", "")
						If PPU.Length=6 Then
							If Regex.IsMatch("\b[A-Z]{4}[0-9]{2}\b", PPU) Or Regex.IsMatch("\b[A-Z]{2}[0-9]{4}\b", PPU) Then
								'Log("PPU:" & PPU)
								FoundPPU(PPU)
							End If
						End If
					Next
				End If
			Catch
				Log(LastException)
			End Try
			
		End If
	End If
End Sub

#Else if B4I
Sub B4XPage_Resize (Width As Float, Height As Float)
	scanner.Resize
End Sub

Private Sub StartCamera
	scanner.Start
	StartCameraShared
End Sub

Sub scanner_Detected (Codes As List)
	If Codes.Size > 0 Then
		Dim code As BarcodeCode = Codes.Get(0)
		FoundBarcode(code.Value)
	End If
End Sub
#End If