'  
'   Rebex Sample Code License
' 
'   Copyright 2026, REBEX CR s.r.o.
'   All rights reserved.
'   https://www.rebex.net/
' 
'   Permission to use, copy, modify, and/or distribute this software for any
'   purpose with or without fee is hereby granted.
' 
'   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
'   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
'   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
'   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
'   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
'   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
'   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
'   OTHER DEALINGS IN THE SOFTWARE.
' 

Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Text
Imports System.Windows.Forms

''' <summary>
''' A simple ListView sorter.
''' </summary>
Public Class ListViewColumnSorter
    Implements IComparer

    Private _column As Integer
    Private _descending As Boolean

    ''' <summary>
    ''' Sets the column according which to sort. Calling it multiple times alternates between ascending/descending sort order.
    ''' </summary>
    ''' <param name="column">A column according which to sort.</param>
    Public Sub SetSortingColumn(ByVal column As Integer)
        If _column = column Then
            _descending = Not _descending
        Else
            _descending = False
        End If

        _column = column
    End Sub

    ''' <summary>
    ''' Compares two instances of ListViewItem.
    ''' </summary>
    ''' <param name="x">First ListViewItem.</param>
    ''' <param name="y">Second ListViewItem.</param>
    ''' <returns>A value indicating whether x is less/equal/greater than y (-1/0/1).</returns>
    Private Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
        Dim item1 As ListViewItem = CType(x, ListViewItem)
        Dim item2 As ListViewItem = CType(y, ListViewItem)

        ' compare item's tag when available
        Dim value1 As IComparable = TryCast(item1.SubItems(_column).Tag, IComparable)
        Dim value2 As IComparable = TryCast(item2.SubItems(_column).Tag, IComparable)

        ' if the tag are not available, use item's text instead
        If value1 Is Nothing Then value1 = item1.SubItems(_column).Text
        If value2 Is Nothing Then value2 = item2.SubItems(_column).Text

        If _descending Then
            Return value2.CompareTo(value1)
        Else
            Return value1.CompareTo(value2)
        End If
    End Function
End Class



