#Const CATCHERROR = True

Imports System.IO

Namespace AdvancedDemo
	Partial Public Class MainForm
		Inherits Form
		Private Const FolderImageIndex As Integer = 0
		Private Const PdfImageIndex As Integer = 1

		Private ReadOnly _exception As Boolean
		Private _lastSelected As TreeNode
		Private _activeController As TemplateExampleBase
		Private ReadOnly _commonExampleController As TemplateExampleBase = New CommonTemplateExample()

		Public Sub New()
			Try
				InitializeComponent()
			Catch exc As ComponentPro.Licensing.TemplateEngine.UltimateLicenseException
				MessageBox.Show(exc.Message, "Error")
				_exception = True
				Return
			End Try
		End Sub

		''' <summary>
		''' Handles the Form's Load event.
		''' </summary>
		''' <param name="e">The event arguments.</param>
		Protected Overrides Sub OnLoad(ByVal e As EventArgs)
			MyBase.OnLoad(e)
			If _exception Then
				Me.Close()
			End If

			BuildTree(Util.SamplesDir, tvSamples.Nodes)
			tvSamples.SelectedNode = tvSamples.Nodes(0)
		End Sub

		Private Sub BuildTree(ByVal folderPath As String, ByVal nodes As TreeNodeCollection)
			Dim node As TreeNode
			Dim di As New DirectoryInfo(folderPath)
			If di.Exists Then
				Dim files() As FileInfo = di.GetFiles("*.tpl")
				For Each f As FileInfo In files
					node = nodes.Add(f.Name.Substring(0, f.Name.Length - 4))
					node.Tag = f.FullName
					node.ImageIndex = PdfImageIndex
					node.SelectedImageIndex = PdfImageIndex
				Next f

				Dim dirs() As DirectoryInfo = di.GetDirectories()
				For Each d As DirectoryInfo In dirs
					node = nodes.Add(d.Name)
					node.Tag = d.FullName
					node.ImageIndex = FolderImageIndex
					BuildTree(d.FullName, node.Nodes)
					node.Expand()
				Next d
			End If
		End Sub

		Private Sub EnableButtons(ByVal enable As Boolean, ByVal hasCS As Boolean, ByVal hasVB As Boolean)
			btnCS.Enabled = hasCS
			btnVB.Enabled = hasVB
			btnGenerate.Enabled = enable
		End Sub

		Friend Shared Function GetControlTypeName(ByVal controlFileName As String) As String
			Dim s As String = "AdvancedDemo.Samples." & controlFileName.Substring(0, controlFileName.Length - 4).Replace(" "c, "_"c).Replace("\"c, "."c).Replace("-"c, "_"c)

			Return s
		End Function

		Private Sub tvSamples_AfterSelect(ByVal sender As Object, ByVal e As TreeViewEventArgs) Handles tvSamples.AfterSelect
			If e.Node.ImageIndex = PdfImageIndex Then
				Dim file As String = CStr(e.Node.Tag)
				Dim p As Integer = file.LastIndexOf("."c)
				Dim fileWithoutExt As String = file.Substring(0, p)
				Dim hasCS As Boolean = System.IO.File.Exists(fileWithoutExt & ".cs")
				Dim hasVB As Boolean = System.IO.File.Exists(fileWithoutExt & ".vb")

				' Load template content
				Using sr As New StreamReader(file)
					txtTemplate.Text = sr.ReadToEnd()
				End Using
				txtOutput.Clear()

				EnableButtons(True, True, True)

				If hasCS OrElse hasVB Then
					Dim tname As String = GetControlTypeName(file.Remove(0, Util.SamplesDir.Length + 1))
					_activeController = CType(Activator.CreateInstance(Type.GetType(tname)), TemplateExampleBase)
				Else
					_activeController = _commonExampleController
				End If

				_lastSelected = e.Node
			Else
				EnableButtons(False, False, False)
			End If
		End Sub

		Private Sub btnGenerate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGenerate.Click
			If _lastSelected IsNot Nothing Then
#If CATCHERROR Then
				Try
#End If
					Dim file As String = CStr(_lastSelected.Tag)
					txtOutput.Text = _activeController.Generate(Path.GetDirectoryName(file), file, txtTemplate.Text)
#If CATCHERROR Then
				Catch exc As Exception
					MessageBox.Show("Error: " & exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
					System.Diagnostics.Trace.WriteLine(exc.StackTrace)

					txtTemplate.Focus()
					Dim dexc As ComponentPro.TemplateEngineException = TryCast(exc, ComponentPro.TemplateEngineException)
					If dexc IsNot Nothing Then
						txtTemplate.Select(dexc.Position, 1)
					End If
				End Try
#End If
			End If
		End Sub

		Private Sub btnCS_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCS.Click
			Dim file As String
			If _activeController IsNot _commonExampleController Then
				file = CStr(_lastSelected.Tag)
				file = file.Substring(0, file.Length - 4) & ".cs"
			Else
				file = Util.SamplesDir & "\CommonTemplateExample.cs"
			End If

			If System.IO.File.Exists(file) Then
				Dim pre As New CodePreview(file, True)
				pre.ShowDialog()
			End If
		End Sub

		Private Sub btnVB_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnVB.Click
			Dim file As String
			If _activeController IsNot _commonExampleController Then
				file = CStr(_lastSelected.Tag)
				file = file.Substring(0, file.Length - 4) & ".vb"
			Else
				file = Util.SamplesDir & "\CommonTemplateExample.vb"
			End If

			If System.IO.File.Exists(file) Then
				Dim pre As New CodePreview(file, False)
				pre.ShowDialog()
			End If
		End Sub
	End Class
End Namespace