//  
//   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.
// 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Rebex.Samples
{
    /// <summary>
    /// A simple ListView sorter.
    /// </summary>
    public class ListViewColumnSorter : IComparer
    {
        private int _column;
        private bool _descending;

        /// <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 void SetSortingColumn(int column)
        {
            if (_column == column)
                _descending = !_descending;
            else
                _descending = false;

            _column = column;
        }

        /// <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>
        int IComparer.Compare(object x, object y)
        {
            ListViewItem item1 = (ListViewItem)x;
            ListViewItem item2 = (ListViewItem)y;

            // compare item's tag when available
            IComparable value1 = item1.SubItems[_column].Tag as IComparable;
            IComparable value2 = item2.SubItems[_column].Tag as IComparable;

            // if the tag are not available, use item's text instead
            if (value1 == null)
                value1 = item1.SubItems[_column].Text;
            if (value2 == null)
                value2 = item2.SubItems[_column].Text;

            if (_descending)
                return value2.CompareTo(value1);
            else
                return value1.CompareTo(value2);
        }
    }
}



