Imports System.Threading
Imports System.ComponentModel
Imports System.Text

Imports Stax
Imports Stax.UI
Imports Stax.AppFramework

Public Class SearchPackageForm
    Inherits ExtendedForm

#Region " Windows Form Designer generated code "

    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    Friend WithEvents bRecentSearches As System.Windows.Forms.Button
    Friend WithEvents bFull As System.Windows.Forms.Button
    Friend WithEvents bQuick As System.Windows.Forms.Button
    Friend WithEvents TipProvider As Stax.UI.TipProvider
    Friend WithEvents SmartTagProvider As Stax.UI.Design.SmartTagProvider
    Friend WithEvents bHelp As System.Windows.Forms.Button
    Friend WithEvents ResultColumnHeader As System.Windows.Forms.ColumnHeader
    Friend WithEvents bCancel As System.Windows.Forms.Button
    Friend WithEvents bOK As System.Windows.Forms.Button
    Friend WithEvents lv As System.Windows.Forms.ListView
    Friend WithEvents tbSearch As System.Windows.Forms.TextBox
    Friend WithEvents VersionColumnHeader As System.Windows.Forms.ColumnHeader
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Me.lv = New System.Windows.Forms.ListView
        Me.ResultColumnHeader = New System.Windows.Forms.ColumnHeader
        Me.VersionColumnHeader = New System.Windows.Forms.ColumnHeader
        Me.bCancel = New System.Windows.Forms.Button
        Me.bOK = New System.Windows.Forms.Button
        Me.bHelp = New System.Windows.Forms.Button
        Me.bRecentSearches = New System.Windows.Forms.Button
        Me.bFull = New System.Windows.Forms.Button
        Me.bQuick = New System.Windows.Forms.Button
        Me.SmartTagProvider = New Stax.UI.Design.SmartTagProvider
        Me.TipProvider = New Stax.UI.TipProvider(Me.components)
        Me.tbSearch = New System.Windows.Forms.TextBox
        CType(Me.TipProvider, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'lv
        '
        Me.lv.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.lv.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.ResultColumnHeader, Me.VersionColumnHeader})
        Me.lv.FullRowSelect = True
        Me.lv.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable
        Me.lv.HideSelection = False
        Me.lv.Location = New System.Drawing.Point(13, 13)
        Me.lv.MultiSelect = False
        Me.lv.Name = "lv"
        Me.lv.Size = New System.Drawing.Size(604, 291)
        Me.lv.TabIndex = 0
        Me.lv.UseCompatibleStateImageBehavior = False
        Me.lv.View = System.Windows.Forms.View.Details
        '
        'ResultColumnHeader
        '
        Me.ResultColumnHeader.Text = "Result"
        Me.ResultColumnHeader.Width = 450
        '
        'VersionColumnHeader
        '
        Me.VersionColumnHeader.Text = "Version"
        Me.VersionColumnHeader.Width = 112
        '
        'bCancel
        '
        Me.bCancel.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.bCancel.Location = New System.Drawing.Point(542, 310)
        Me.bCancel.Name = "bCancel"
        Me.bCancel.Size = New System.Drawing.Size(75, 24)
        Me.bCancel.TabIndex = 1
        Me.bCancel.Text = "Cancel"
        '
        'bOK
        '
        Me.bOK.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.bOK.DialogResult = System.Windows.Forms.DialogResult.OK
        Me.bOK.Enabled = False
        Me.bOK.Location = New System.Drawing.Point(461, 310)
        Me.bOK.Name = "bOK"
        Me.bOK.Size = New System.Drawing.Size(75, 24)
        Me.bOK.TabIndex = 2
        Me.bOK.Text = "OK"
        '
        'bHelp
        '
        Me.bHelp.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.bHelp.Location = New System.Drawing.Point(364, 310)
        Me.bHelp.Name = "bHelp"
        Me.bHelp.Size = New System.Drawing.Size(75, 24)
        Me.bHelp.TabIndex = 4
        Me.bHelp.Text = "Help"
        Me.bHelp.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText
        '
        'bRecentSearches
        '
        Me.bRecentSearches.Location = New System.Drawing.Point(283, 310)
        Me.bRecentSearches.Name = "bRecentSearches"
        Me.bRecentSearches.Size = New System.Drawing.Size(75, 24)
        Me.bRecentSearches.TabIndex = 3
        Me.bRecentSearches.Text = "   Recent"
        Me.bRecentSearches.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        Me.TipProvider.SetTipText(Me.bRecentSearches, "Quick access of recently performed Full Searches.")
        '
        'bFull
        '
        Me.bFull.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.bFull.Location = New System.Drawing.Point(202, 310)
        Me.bFull.Name = "bFull"
        Me.bFull.Size = New System.Drawing.Size(75, 24)
        Me.bFull.TabIndex = 2
        Me.bFull.Text = "Full..."
        Me.TipProvider.SetTipText(Me.bFull, "Full Search scans the hard drive starting at a specified directory.")
        '
        'bQuick
        '
        Me.bQuick.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.bQuick.Location = New System.Drawing.Point(121, 310)
        Me.bQuick.Name = "bQuick"
        Me.bQuick.Size = New System.Drawing.Size(75, 24)
        Me.bQuick.TabIndex = 1
        Me.bQuick.Text = "Quick"
        Me.TipProvider.SetTipText(Me.bQuick, "Quick Search searches in the registry for hints about possible locations of the a" & _
                "pplication.")
        '
        'tbSearch
        '
        Me.tbSearch.Anchor = CType(((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.tbSearch.BorderStyle = System.Windows.Forms.BorderStyle.None
        Me.tbSearch.Location = New System.Drawing.Point(12, 291)
        Me.tbSearch.Name = "tbSearch"
        Me.tbSearch.ReadOnly = True
        Me.tbSearch.Size = New System.Drawing.Size(605, 13)
        Me.tbSearch.TabIndex = 5
        '
        'SearchPackageForm
        '
        Me.AcceptButton = Me.bOK
        Me.CancelButton = Me.bCancel
        Me.ClientSize = New System.Drawing.Size(629, 346)
        Me.Controls.Add(Me.lv)
        Me.Controls.Add(Me.tbSearch)
        Me.Controls.Add(Me.bRecentSearches)
        Me.Controls.Add(Me.bHelp)
        Me.Controls.Add(Me.bFull)
        Me.Controls.Add(Me.bCancel)
        Me.Controls.Add(Me.bQuick)
        Me.Controls.Add(Me.bOK)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
        Me.HelpButton = True
        Me.MaximizeBox = False
        Me.MinimizeBox = False
        Me.Name = "SearchPackageForm"
        Me.ShowInTaskbar = False
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent
        Me.Text = "Search"
        CType(Me.TipProvider, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub

#End Region

    Private Package As Package
    Private StartDir As String
    Private Cancel As New CancelEventArgs
    Private RecentSearchesMenu As New ContextMenuStrip
    Private Files As Integer

    Public Sub New(ByVal package As Package)
        MyBase.New()
        InitializeComponent()
        Me.Package = package
        QuickSearch()
        UpdateRecentPackageSearchMenu()
    End Sub

    Public Sub QuickSearch()
        lv.Items.Clear()

        For Each i As String In Package.GetSearchResult
            AddItem(i)
        Next
    End Sub

    Public Sub FullSearch(ByVal startDir As String)
        If Directory.Exists(startDir) Then
            Me.StartDir = startDir
            lv.Items.Clear()

            lv.Height -= 20
            DirectoryHelp.FileCallback(startDir, New ParamDelegate(Of String)(AddressOf FilePathsHandler), Cancel, True)
            lv.Height += 20
            Files = 0
            AfterSearch()
        Else
            Msg.Show("The directory doesn't exist.", MsgIcon.Warning)
            s.RecentPackageSearchDirs.Remove(startDir)
            UpdateRecentPackageSearchMenu()
        End If
    End Sub

    Private Sub FilePathsHandler(ByVal path As String)
        Files += 1

        If Files Mod 50 = 0 Then
            tbSearch.Text = path
            Application.DoEvents()
        End If

        If String.Compare(Filepath.GetNameWithExt(path), _
            Package.Filename, StringComparison.OrdinalIgnoreCase) = 0 Then

            AddItem(path)
        End If
    End Sub

    Private Sub AddItem(ByVal path As String)
        Dim version As String = ""

        If path <> "" Then
            If Package.IsCorrectVersion(path) Then
                version = Package.Version
            Else
                version = "Unknown"
            End If
        Else
            path = "File don't exist"
        End If

        Dim lvi As New ListViewItem(New String() {path, version})

        If Package.Version <> "" AndAlso Package.Version = version Then
            lvi.Selected = True
            ActiveControl = bOK
        End If

        lv.Items.Add(lvi)
    End Sub

    Private Sub bOK_Click(ByVal sender As Object, ByVal e As EventArgs) Handles bOK.Click
        Package.SetPath(lv.SelectedItems(0).SubItems(0).Text)
        Close()
    End Sub

    Private Sub lv_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lv.SelectedIndexChanged
        bOK.Enabled = False

        If lv.SelectedItems.Count > 0 Then
            bOK.Enabled = lv.SelectedItems(0).Text.Contains(":")
        End If
    End Sub

    Private Sub lv_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) Handles lv.DoubleClick
        If lv.SelectedItems.Count > 0 Then
            bOK.PerformClick()
        End If
    End Sub

    Private Sub UpdateRecentPackageSearchMenu()
        RecentSearchesMenu.Items.Clear()

        For Each i As String In s.RecentPackageSearchDirs
            Dim item As New ToolStripMenuItem
            item.Text = i
            AddHandler item.Click, AddressOf RecentSearchesClick
            RecentSearchesMenu.Items.Add(item)
        Next
    End Sub

    Private Sub RecentSearchesClick(ByVal sender As Object, ByVal e As EventArgs)
        FullSearch(CType(sender, ToolStripMenuItem).Text)
    End Sub

    Private Sub SearchPackageForm_ActivatedFirstTime() Handles Me.ActivatedFirstTime
        If Not s.StringList.Contains(Me.GetType.FullName) Then
            bHelp.PerformClick()
            s.StringList.Add(Me.GetType.FullName)
        End If
    End Sub

    Private Sub PackageSearchForm_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles MyBase.FormClosing
        Cancel.Cancel = True
    End Sub

    Private Sub bRecentSearches_Click(ByVal sender As Object, ByVal e As EventArgs) Handles bRecentSearches.Click
        If RecentSearchesMenu.Items.Count = 0 Then
            Msg.Show("Please perform a Full Search first.", MsgIcon.Warning)
        Else
            RecentSearchesMenu.Show(bRecentSearches, 0, bRecentSearches.Height)
        End If
    End Sub

    Private Sub bQuickSearch_Click(ByVal sender As Object, ByVal e As EventArgs) Handles bQuick.Click
        QuickSearch()
        AfterSearch()
    End Sub

    Private Sub AfterSearch()
        Dim message As String = Nothing

        If lv.Items.Count = 0 Then
            message = "No applications found."
        ElseIf lv.Items.Count = 1 Then
            message = "1 application found."
        Else
            message = lv.Items.Count.ToString + " applications found."
        End If

        Msg.Show(message, "Search Result", MsgIcon.Info)
    End Sub

    Private Sub bRecentSearches_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles bRecentSearches.Paint
        ButtonHelp.DrawDropDownGlyph(bRecentSearches, e.Graphics, HorizontalAlignment.Right)
    End Sub

    Private Sub bFullSearch_Click(ByVal sender As Object, ByVal e As EventArgs) Handles bFull.Click
        Dim d As New FolderBrowserDialog
        d.ShowNewFolderButton = False
        d.Description = "Please select a directory to scan."

        If d.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Misc.UpdateMostRecentList(s.RecentPackageSearchDirs, d.SelectedPath, 5)
            UpdateRecentPackageSearchMenu()
            FullSearch(d.SelectedPath)
        End If

        d.Dispose()
    End Sub

    Private Sub bHelp_Click(ByVal sender As Object, ByVal e As EventArgs) Handles bHelp.Click
        HelpForm.ShowDialog(Text, TipProvider.GetTips, "In order to use a application StaxRip must know where the application is located. The Search dialog provides two different methods for searching a applications.")
    End Sub

    Private Sub bCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles bCancel.Click
        Close()
    End Sub
End Class