﻿B4J=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=6.01
@EndOfDesignText@
#Event: Click

Sub Class_Globals
	Private mEventName As String 'ignore
	Private mCallBack As Object 'ignore
	Private mBase As B4XView 'ignore
	Private xui As XUI 'ignore
	Private mPattern As String
	Private const NUM_CHARS As Int = 6
	Private cvs As B4XCanvas
	Private mCaptcha As B4XView
	
End Sub

Public Sub Initialize (Callback As Object, EventName As String)
	mEventName = EventName
	mCallBack = Callback
	
End Sub

Public Sub DesignerCreateView (Base As Object, Lbl As Label, Props As Map)
	mBase = Base
	cvs.Initialize(mBase)
	mCaptcha = xui.CreatePanel("Captcha")
	mBase.AddView(mCaptcha,0,0, mBase.Width, mBase.Height)
	Refresh
End Sub

Public Sub Refresh
	CreatePattern
	DrawPattern
End Sub

Private Sub CreatePattern
	Dim sb As StringBuilder
	sb.Initialize
	Dim possible As List
	possible.Initialize
	
	For Each Pair() As Object In Array(Array(Asc("A"), Asc("Z")), Array(Asc("a"), Asc("z")), Array(Asc("0"), Asc("9")))
		Dim first = Pair(0), last = Pair(1) As Int
		For i = first To last
			Dim s As String = Chr(i) 'this is required in B4i. Otherwise the Char value will be casted to a number.
			possible.Add(s)
		Next
	Next
	For i = 0 To NUM_CHARS - 1
		 sb.Append(possible.Get(Rnd(0, possible.Size)))
	Next
	mPattern = sb.ToString
End Sub

Private Sub DrawPattern
	cvs.DrawRect(cvs.TargetRect, Rnd(0xFFBBBBBB, -1), True, 0)
	Dim left As Int
	For i = 0 To mPattern.Length - 1
		Dim gap As Int = Rnd(20dip, 60dip)
		left = left + gap
		cvs.DrawTextRotated(mPattern.CharAt(i), left, mBase.Height * 0.7 + Rnd(-10dip, 10dip), _
			xui.CreateDefaultFont(Rnd(18, 28)), Rnd(0xFF000000, 0xFF888888), "CENTER", Rnd(-45, 45))
	Next
	For i = 1 To 5
		cvs.DrawCircle(Rnd(0, mBase.Width), Rnd(0, mBase.Height), Rnd(1dip, 30dip), Rnd(0x88000000, 0x88FFFFFF), True, 2dip)
	Next
	For i = 1 To 4
		cvs.DrawLine(Rnd(0, 30dip), Rnd(0, mBase.Height), mBase.Width - Rnd(0, 30dip), Rnd(0, mBase.Height), Rnd(0x88000000, 0x88FFFFFF), _
			Rnd(1dip, 4dip))
	Next
	For i = 1 To 3
		Dim x1, y1 As Int
		Dim a As Int = Rnd(2, 10)
		Dim clr As Int = Rnd(0xFF000000, 0xFF888888)
		Dim y0 As Int = Rnd(0, mBase.Height)
		For x = 0 To mBase.Width
			Dim y As Float = y0 + a * Sin(x / 10)
			cvs.DrawLine(x1, y1, x, y, clr, 1dip)
			x1 = x
			y1 = y
		Next
	Next
	cvs.Invalidate
End Sub

Public Sub IsMatch(s As String) As Boolean
	Return s.ToLowerCase = mPattern.ToLowerCase
End Sub


Private Sub Base_Resize (Width As Double, Height As Double)
  
End Sub

#If B4A or B4I
Private Sub Captcha_Click
#Else B4J
Private Sub Captcha_MouseClicked (EventData As MouseEvent)
#End if
	If xui.SubExists(mCallBack, mEventName & "_Click",0) Then
		CallSub(mCallBack, mEventName & "_Click")
	End If
End Sub

	