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

namespace Aqua877.WinApp.IronLivetube
{
	public class MainWindowListViewSorter : IComparer
	{
		private int _Column;
		private SortOrder _Order;

		public int Column
		{
			set
			{
				if (this._Column == value)
				{
					if (this._Order == SortOrder.Ascending)
					{
						this._Order = SortOrder.Descending;
					}
					else if (this._Order == SortOrder.Descending)
					{
						this._Order = SortOrder.Ascending;
					}
				}
				this._Column = value;
			}
			get
			{
				return this._Column;
			}
		}

		public SortOrder Order
		{
			set
			{
				this._Order = value;
			}
			get
			{
				return this._Order;
			}
		}

		public MainWindowListViewSorter(int column, SortOrder order)
		{
			this._Column = column;
			this._Order = order;
		}

		public MainWindowListViewSorter()
		{
			this._Column = 0;
			this._Order = SortOrder.Ascending;
		}

		public int Compare(object x, object y)
		{
			int result = 0;

			var itemx = x as ListViewItem;
			var itemy = y as ListViewItem;

			switch (this.Column)
			{
				case 0:
				{
					if (itemx.SubItems[this._Column].Text == "")
					{
						if (itemy.SubItems[this._Column].Text == "")
						{
							result = 0;
						}
						else
						{
							result = -1;
						}
					}
					else if (itemy.SubItems[this._Column].Text == "")
					{
						result = 1;
					}
					else
					{
						result = int.Parse(itemx.SubItems[0].Text).CompareTo(int.Parse(itemy.SubItems[0].Text));
						break;
					}
					break;
				}

				case 1:
				{
					result = 0;
					break;
				}

				case 2:
				case 3:
				case 5:
				case 6:
				{
					if (itemx.SubItems[this._Column].Text == "")
					{
						if (itemy.SubItems[this._Column].Text == "")
						{
							result = 0;
						}
						else
						{
							result = -1;
						}
					}
					else if (itemy.SubItems[this._Column].Text == "")
					{
						result = 1;
					}
					else
					{
						result = string.Compare(itemx.SubItems[this._Column].Text, itemy.SubItems[this._Column].Text);
					}
					break;
				}

				case 4:
				{
					result = DateTime.Compare(
						DateTime.ParseExact(itemx.SubItems[4].Text, "M/d H:m:s", null),
						DateTime.ParseExact(itemy.SubItems[4].Text, "M/d H:m:s", null)
					);
					break;
				}
			}

			if (this._Order == SortOrder.Descending)
			{
				result = -result;
			}
			else if (this._Order == SortOrder.None)
			{
				result = 0;
			}
			return result;
		}
	}
}
