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

namespace skyscraper5.UI
{
	internal class PidListViewItemSorter : IComparer
	{
		public PidListViewItemSorter()
		{
			SorterInstanceGuid = Guid.NewGuid();
		}

		public Guid SorterInstanceGuid { get; private set; }

		public int SortColumn { get; internal set; }

		public SortOrder Order { get; internal set; }

		public int Compare(object? x, object? y)
		{
			PidListViewItem x2 = x as PidListViewItem;
			PidListViewItem y2 = y as PidListViewItem;

			int value;

			switch(SortColumn)
			{
				case 0: value = x2.PID.CompareTo(y2.PID); break;
				case 1: value = x2.PackagesInPid.CompareTo(y2.PackagesInPid); break;
				case 2: value = x2.PackagesInPid.CompareTo(y2.PackagesInPid); break;
				case 3: value = CompareProgramName(x2.ProgramName,y2.ProgramName,Order); break;
				case 4: value = CompareProgramName(x2.UsageLabel, y2.UsageLabel, Order); break;
				default:
					throw new NotImplementedException(String.Format("{0}, {1}", SortColumn, Order));
			}

			if (Order == SortOrder.Descending)
				value /= -1;

			return value;
		}

		private int CompareProgramName(string x3, string y3, SortOrder sortOrder)
		{
			if (string.IsNullOrEmpty(x3) && string.IsNullOrEmpty(y3))
				return 0;

			if (string.IsNullOrEmpty(x3))
				return sortOrder == SortOrder.Descending ? -1 : 1;

			if (string.IsNullOrEmpty(y3))
				return sortOrder == SortOrder.Descending ? 1 : -1;

			return x3.CompareTo(y3);
		}
	}
}
