Option Explicit On
Imports System.Linq
Imports System.Collections.Generic
Imports gmRTL.MSComCtlLib
Namespace FileExplorer
   Public Class frmExploreLite : Inherits System.Windows.Forms.Form
      Private Dim _disposed As Boolean = False
      <System.Diagnostics.DebuggerNonUserCode()> _
      Public Sub New()
         MyBase.New()
         'This call is required by the Windows Form Designer.
         InitializeComponent()
         'Add any initialization after the InitializeComponent() call
         If (DesignMode) Then Exit Sub
         Me.Toolbar1_Button1.Name = "up"
         Me.Toolbar1_Button2.Name = "down"
         Me.Toolbar1_Button4.Name = "open"
         Me.Toolbar1_Button5.Name = "close"
         Me.Toolbar1_Button8.Name = "info"
         Form_Load(Nothing, Nothing)
         Form_Resize(Nothing, Nothing)

      End Sub
      'Form overrides dispose to clean up the component list.
      <System.Diagnostics.DebuggerNonUserCode()> _
      Protected Overloads Overrides Sub Dispose(ByVal Disposing As Boolean)
         If _disposed Then
            Return
         End If
         If Disposing Then
            If Not components Is Nothing Then
               components.Dispose()
            End If
         End If
         _disposed = True
         MyBase.Dispose(Disposing)
      End Sub
      Private mIsMoving As Boolean = False ' Is splitter in motion?
      Private Const mSplitLimit As Integer = (2000)/15 ' Minimum width for TreeView and ListView
      Private Sub Form_Load(ByVal sender As Object, ByVal e As EventArgs)
         Dim currFldr As System.IO.DirectoryInfo = Nothing
         Dim nodRoot As System.Windows.Forms.TreeNode = Nothing


         ' Set column widths
         lvListView.Columns(0).Width = 186
         lvListView.Columns(1).Width = 72
         lvListView.Columns(2).Width = 67
         lvListView.Columns(3).Width = 79
         lvListView.Columns(4).Width = 133

         ' Populate level 1 of the TreeView
         DoHourglass(True)
         Dim drvTemp As String
         For Each drvTemp in System.IO.Directory.GetLogicalDrives()
            Dim drv As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(drvTemp)
            ' Proceed only if the drive is ready.
            ' This ignores an empty CD drive, for example.
            If (drv.Exists) Then
               nodRoot = tvTreeView.Nodes.Add(drv.Root.FullName,drv.Root.FullName.Substring(0,1) & ":\")
               nodRoot.ImageKey = "drive"
               nodRoot.SelectedImageKey = "drive"
               nodRoot.TreeView.Sort() ' = True

               ' Get a pointer to the root folder
               currFldr = drv.Root

               ' Populate level 2 of the TreeView
               For Each fldr As System.IO.DirectoryInfo In currFldr.GetDirectories()
                  AddTVNode(nodRoot,drv.Root.FullName.Substring(0,1) & "\" & fldr.Name,fldr.Name)
               Next
            End If
         Next

         ' Set up the first node
         nodRoot = tvTreeView.Nodes(0)
         nodRoot.EnsureVisible()
         nodRoot.TreeView.SelectedNode = nodRoot
         nodRoot.Expand()
         lblPath.Text = nodRoot.FullPath
         tvTreeView_NodeClick(Nothing,New TreeViewEventArgs(nodRoot))

         DoHourglass(False)
         System.Windows.Forms.Application.DoEvents()
      End Sub
      Private Sub Form_Resize(ByVal sender As Object, ByVal e As EventArgs)
         If (Me.ClientRectangle.Width = 0) Then
            Exit Sub
         End If
         If (Me.Width < 200) Then
            Me.Width = 200
         End If
         If (Me.Height < 200) Then
            Me.Height = 200
         End If

         Dim formWidth As Integer = 0
         formWidth = Me.ClientRectangle.Width

         Dim formHeight As Integer = 0
         formHeight = Me.ClientRectangle.Height - formHeight - tvTreeView.Top - sbStatusBar.Height - 1

         tvTreeView.Height = formHeight * 0.5

         lstCheckedTVItems.Width = tvTreeView.Width
         lstCheckedTVItems.Top = tvTreeView.Top + tvTreeView.Height + 1
         lstCheckedTVItems.Height = formHeight - (tvTreeView.Height + 1)

         lvListView.Width = formWidth - tvTreeView.Width - 8
         lvListView.Height = formHeight * 0.5

         RichTextBox1.Width = formWidth - tvTreeView.Width - 8
         RichTextBox1.Top = lvListView.Top + lvListView.Height + 1
         RichTextBox1.Height = formHeight - (lvListView.Height + 1)

         imgSplitter.Top = tvTreeView.Top + 2
         imgSplitter.Height = formHeight - 60.0!
         SizeControls(imgSplitter.Left)

      End Sub
      Private Sub imgSplitter_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
         ' Use the PictureBox as a marker for the new split location
         picSplitter.SetBounds(imgSplitter.Left,imgSplitter.Top,imgSplitter.Width \ 4,imgSplitter.Height - 1)
         picSplitter.Visible = True
         mIsMoving = True
      End Sub
      Private Sub imgSplitter_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
         Dim X As Single
         X = e.X
         Dim sglPos As Single = 0.0F

         If (mIsMoving) Then
            sglPos = X + imgSplitter.Left
            If (sglPos < mSplitLimit) Then
               picSplitter.Left = mSplitLimit
            ElseIf (sglPos > Me.Width - mSplitLimit) Then
               picSplitter.Left = Me.Width - mSplitLimit
            Else
               picSplitter.Left = sglPos
            End If
         End If
      End Sub
      Private Sub imgSplitter_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
         SizeControls(picSplitter.Left)
         picSplitter.Visible = False
         mIsMoving = False
      End Sub
      Private Sub lvListView_ColumnClick(ByVal sender As Object, ByVal e As ColumnClickEventArgs)
         Dim ColumnHeader As System.Windows.Forms.ColumnHeader
         ColumnHeader = CType(sender, ListView).Columns(e.Column)

         'Sort the columnn that the user clicked.
         If (lvListView.GetSortKey() <> ColumnHeader.Index - 1) Then
            lvListView.SetSortKey(ColumnHeader.Index - 1)
            lvListView.ListViewItemSorter = new gmRTL.MSComCtlLib.ListViewSorter(lvListView.SetSortOrder(System.Windows.Forms.SortOrder.Ascending), lvListView.GetSortKey())
         Else
            If (lvListView.Sorting = System.Windows.Forms.SortOrder.Ascending) Then
               lvListView.ListViewItemSorter = new gmRTL.MSComCtlLib.ListViewSorter(lvListView.SetSortOrder(System.Windows.Forms.SortOrder.Descending), lvListView.GetSortKey())
            Else
               lvListView.ListViewItemSorter = new gmRTL.MSComCtlLib.ListViewSorter(lvListView.SetSortOrder(System.Windows.Forms.SortOrder.Ascending), lvListView.GetSortKey())
            End If
         End If
      End Sub
      Private Sub lvListView_ItemClick(ByVal sender As Object, ByVal e As ListViewItemSelectionChangedEventArgs)
         Dim Item As System.Windows.Forms.ListViewItem
         Item = e.Item
         If (Not Item.Selected) Then Exit Sub
         Dim ts As System.IO.StreamReader = Nothing
         Dim fPath As String = ""
         Try
            gmRTL.Core.GlobalException.ClearErrorObject()


            fPath = System.IO.Path.Combine(lblPath.Text,Item.Text)

            If (new System.IO.FileInfo(fPath).Length > 10000) Then
               Err.Raise(17,String.Empty,"File too big")
            End If

            ts = new System.IO.StreamReader(new System.IO.FileStream(fPath,System.IO.FileMode.Open,System.IO.FileAccess.Read,System.IO.FileShare.ReadWrite))


            RichTextBox1.Text = ts.ReadToEnd()

         Catch exc As System.Exception
            gmRTL.Core.GlobalException.SetErrorObject(exc)
         End Try
         If (Err.Number <> 0) Then
            RichTextBox1.Text = "Error opening " & fPath & Environment.NewLine & "Err=" & Err.Description
            Interaction.Beep()
         End If
         If (Not (ts Is Nothing)) Then
            ts.Close()
         End If

      End Sub
      Private Sub mnu_FileExit_Click(ByVal sender As Object, ByVal e As EventArgs)
         Me.Close()
      End Sub
      Private Sub mnuTestTreeViewCheckboxes_Click(ByVal sender As Object, ByVal e As EventArgs)
         tvTreeView.CheckBoxes = Not tvTreeView.CheckBoxes
      End Sub
      Private Sub RichTextBox1_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
         Dim keyCode As Integer
         keyCode = e.KeyCode
         Interaction.Beep()
         keyCode = 0
      End Sub
      Private Sub Toolbar1_ButtonClick(ByVal sender As Object, ByVal e As ToolStripItemClickedEventArgs)
         Dim Button As System.Windows.Forms.ToolStripItem
         Button = DirectCast(e.ClickedItem,System.Windows.Forms.ToolStripItem)


         Dim itm As System.Windows.Forms.ListViewItem = Nothing

         Dim i As Integer = 0
         Try
            gmRTL.Core.GlobalException.ClearErrorObject()
            If (Button.Text = "up") Then
               tvTreeView.SelectedNode.PrevNode.TreeView.SelectedNode = tvTreeView.SelectedNode.PrevNode
            End If
            If (Button.Text = "down") Then
               tvTreeView.SelectedNode.NextNode.TreeView.SelectedNode = tvTreeView.SelectedNode.NextNode
            End If
            If (Button.Text = "open") Then
               tvTreeView.SelectedNode.Expand()
            End If
            If (Button.Text = "close") Then
               tvTreeView.SelectedNode.Collapse()
            End If
            If (Button.Text = "tagit") Then
               Dim minsize As Decimal = 0.00
               minsize = -1
               Dim cursize As Decimal = 0.00
               Dim smallest As Integer = 0
               Dim forTemp0 As System.Windows.Forms.ListViewItem
               For Each forTemp0 in lvListView.Items
                  itm = forTemp0
                  cursize = CDec(Strings.Trim(itm.SubItems(1).Text))
                  If (cursize < minsize Or minsize < 0) Then
                     minsize = cursize
                     smallest = itm.Index+1
                  End If
               Next
               lvListView.FocusedItem = lvListView.Items(smallest - 1)
               itm = lvListView.SelectedItems(0)
               itm.Font = gmRTL.GUI.FontHelper.SetBold(itm.Font, True)
               lvListView.SelectedItems(0).SubItems(4).Text = "smallest"
            End If
            If (Button.Text = "info") Then
               itm = lvListView.SelectedItems(0)
               If (itm Is Nothing) Then
                  RichTextBox1.Text = "Select an Item"
               Else
                  lvListView.SelectedItems(0).Font = gmRTL.GUI.FontHelper.SetBold(lvListView.SelectedItems(0).Font, True)
                  RichTextBox1.Text = "" & "name:" & itm.Text & Environment.NewLine & "size:" & itm.SubItems(1).Text & Environment.NewLine & "ext :" & itm.SubItems(2).Text & Environment.NewLine & "date:" & itm.SubItems(3).Text & Environment.NewLine & "tag :" & itm.SubItems(4).Text
               End If
            End If
         Catch exc As System.Exception
            gmRTL.Core.GlobalException.SetErrorObject(exc)
         End Try
         If (Err.Number <> 0) Then
            RichTextBox1.Rtf = "ERROR: " & Err.Description
            Interaction.Beep()
         End If

      End Sub
      Private Sub tvTreeView_DblClick(ByVal sender As Object, ByVal e As EventArgs)
         If (tvTreeView.SelectedNode.Index <> 0 And tvTreeView.SelectedNode.GetNodeCount(false) <> 0) Then
            writeLog("tvTreeView_DblClick: not the root node and has children")
         End If
      End Sub
      Private Sub tvTreeView_NodeCheck(ByVal sender As Object, ByVal e As TreeViewEventArgs)
         Dim Node As System.Windows.Forms.TreeNode
         Node = e.Node
         Dim rpt As String = ""
         rpt = lstCheckedTVItems.Items.Count & ": " & Node.Text & IIf(Node.Checked," checked"," unchecked")
         writeLog(rpt)
         lstCheckedTVItems.Items.Add(rpt)
      End Sub
      ' This needs a complex migration.  The event is is not raised for the toolbar but for individual menu items.
      ' This handler would need to be attached to all ButtonMenu items in the ToolBar.
      '
      ' Private Sub Toolbar1_ButtonMenuClick(ByVal ButtonMenu As MSComctlLib.ButtonMenu)
      '    lvListView.SelectedItem.SubItems(4) = ButtonMenu.Text
      ' End Sub
      Private Sub tvTreeView_NodeClick(ByVal sender As Object, ByVal e As TreeViewEventArgs)
         Dim Node As System.Windows.Forms.TreeNode
         Node = e.Node
         Dim currFldr As System.IO.DirectoryInfo = Nothing

         If (tvTreeView.SelectedNode.Index <> 0 And tvTreeView.SelectedNode.GetNodeCount(false) <> 0) Then
            writeLog("tvTreeView_NodeClick: not the root node and has children")
         End If


         currFldr = new System.IO.DirectoryInfo(Node.FullPath)
         lblPath.Text = Node.FullPath

         DoHourglass(True)

         ' Add child nodes only if there aren't any now
         If (Node.GetNodeCount(false) = 0) Then
            For Each fldr As System.IO.DirectoryInfo In currFldr.GetDirectories()
               AddTVNode(Node,Node.Name & "\" & fldr.Name,fldr.Name)
            Next
            Node.Expand()
         End If

         ' Add files to the ListView
         lvListView.Items.Clear()
         Dim totalFileSize As Single = 0.0F

         For Each fl As System.IO.FileInfo In currFldr.GetFiles()
            totalFileSize = totalFileSize + fl.Length
            AddListItem("",fl.Name,Convert.ToString(fl.Length),System.IO.Path.GetExtension(fl.FullName),fl.LastWriteTime)
         Next

         ' Show total files and space occupied
         Dim fileCtr As Integer = 0
         Dim message As String = ""

         fileCtr = currFldr.GetFiles().Length
         message = fileCtr & " file" & IIf(fileCtr = 1,"  ","s  ")
         message = message & gmRTL.Core.FormatHelper.Format(totalFileSize,"###,###,##0") & " bytes"
         sbStatusBar.Items(0).Text = message & " tvTreeView.SelectedItem.Index = " & tvTreeView.SelectedNode.Index
         DoHourglass(False)

         writeLog(message & " tvTreeView.SelectedItem.Index = " & tvTreeView.SelectedNode.Index)

         System.Windows.Forms.Application.DoEvents()
      End Sub
      Private Sub AddListItem(ByVal itemKey As String,ByVal itemText As String,ByVal itemSize As String,ByVal itemType As String,ByVal itemModified As DateTime)

         ' Add a ListItem, then additional columns as ListSubItems.
         Dim liListItem As System.Windows.Forms.ListViewItem = Nothing
         liListItem = lvListView.Items.Add(itemText,"genericSmall")

         Dim withTemp1 As System.Windows.Forms.ListViewItem.ListViewSubItemCollection = Nothing
         withTemp1 = liListItem.SubItems
         withTemp1.Add(itemSize)
         withTemp1.Add(itemType)
         withTemp1.Add(itemModified)
         withTemp1.Add("no")
         liListItem.Selected = False

      End Sub
      Private Sub AddTVNode(ByVal ParentNode As System.Windows.Forms.TreeNode,ByVal nodeKey As String,ByVal nodeText As String)
         ' Add a new TreeView node.
         Dim newNode As System.Windows.Forms.TreeNode = Nothing
         newNode = ParentNode.Nodes.Add(nodeKey,nodeText,ilMain.Images.IndexOfKey("fldrClosed"),ilMain.Images.IndexOfKey("fldrOpen"))
      End Sub
      Dim Shared DoHourglass_hourGlassCtr As Integer = 0
      Private Sub DoHourglass(ByVal showHourglass As Boolean)
         ' Turns hourglass display on/off.
         ' Keeps track of how many nested calls have been made to the hourglass function.
         '
         ' Was the cursor already an hourglass?
         Dim isHourglassPrev As Boolean = False
         ' Is the cursor an hourglass now?
         Dim isHourglassNow As Boolean = False
         ' How many nested routines have turned on the hourglass?

         ' Note the current state of the cursor, then
         ' update the hourglass counter.
         isHourglassPrev = DoHourglass_hourGlassCtr > 0
         If (showHourglass) Then
            DoHourglass_hourGlassCtr = DoHourglass_hourGlassCtr + 1
         Else
            DoHourglass_hourGlassCtr = DoHourglass_hourGlassCtr - 1
         End If
         If (DoHourglass_hourGlassCtr < 0) Then
            DoHourglass_hourGlassCtr = 0
         End If

         ' Set the cursor, but only if it's different from what it is now.
         isHourglassNow = DoHourglass_hourGlassCtr > 0
         If (isHourglassNow <> isHourglassPrev) Then
            If (DoHourglass_hourGlassCtr > 0) Then
               System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
            Else
               System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
            End If
         End If
      End Sub
      Public Sub SizeControls(ByVal X As Integer)
         ' Set sizes and locations for the movable controls
         Try
            gmRTL.Core.GlobalException.ClearErrorObject()

            'Set the TreeView's width
            If (X < 100) Then
               X = 100
            End If
            If (X > Me.Width - 100) Then
               X = Me.Width - 100
            End If
            tvTreeView.Width = X
            lstCheckedTVItems.Width = X
            imgSplitter.Left = X

            ' Set up the ListView
            lvListView.Left = X + 5
            lvListView.Width = Me.Width - (tvTreeView.Width + 13)
            lblPath.Left = lvListView.Left + 2
            lblPath.Width = lvListView.Width - 4
            RichTextBox1.Left = lvListView.Left
            RichTextBox1.Width = lvListView.Width
         Catch exc As System.Exception
            gmRTL.Core.GlobalException.SetErrorObject(exc)
         End Try
         ' trying to resize during minimize?
      End Sub
      Private Sub writeLog(ByVal msg As String)
         Debug.WriteLine(msg)
      End Sub
   End Class
End Namespace
