using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Collections;
using System.Windows.Forms;

namespace PrintListView
{
    // Compares two ListView items based on a selected column.
    public class ListViewComparer : IComparer
    {
        private int ColumnNumber;
        private SortOrder SortOrder;

        public ListViewComparer(int columnNumber, SortOrder sortOrder)
        {
            ColumnNumber = columnNumber;
            SortOrder = sortOrder;
        }

        // Compare two ListViewItems.
        public int Compare(object x, object y)
        {
            // Get the ListViewItems.
            ListViewItem xitem = x as ListViewItem;
            ListViewItem yitem = y as ListViewItem;

            // Get the corresponding sub-item values.
            string xstring;
            if (xitem.SubItems.Count <= ColumnNumber) xstring = "";
            else xstring = xitem.SubItems[ColumnNumber].Text;

            string ystring;
            if (yitem.SubItems.Count <= ColumnNumber) ystring = "";
            else ystring = yitem.SubItems[ColumnNumber].Text;

            // Compare them.
            int result;

            // See if the values look like numbers.
            double xdouble, ydouble;
            if (double.TryParse(xstring, out xdouble) &&
                double.TryParse(ystring, out ydouble))
            {
                // Treat as a number.
                result = xdouble.CompareTo(ydouble);
            }
            else
            {
                // See if the values look like dates.
                DateTime xdate, ydate;
                if (DateTime.TryParse(xstring, out xdate) &&
                    DateTime.TryParse(ystring, out ydate))
                {
                    // Treat as a date.
                    result = xdate.CompareTo(ydate);
                }
                else
                {
                    // Treat as a string.
                    result = xstring.CompareTo(ystring);
                }
            }

            // Return the result depending on sort order.
            if (SortOrder == SortOrder.Ascending) return result;
            return -result;
        }
    }
}
