using skyscraper5.Skyscraper.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SDL2Demo.Net
{
    public sealed class IpTrafficInfoComparer : IComparer<KeyValuePair<IpTrafficInfo, IpPerformanceInfo>>
    {
		public IpTrafficInfoComparer(IpTrafficInfoComparerMode mode = IpTrafficInfoComparerMode.ByNumPackets)
		{
			ComparisionMode = mode;
		}

        public IpTrafficInfoComparerMode ComparisionMode { get; set; }
        public int Compare(KeyValuePair<IpTrafficInfo, IpPerformanceInfo> x, KeyValuePair<IpTrafficInfo, IpPerformanceInfo> y)
        {
			switch(ComparisionMode)
			{
				case IpTrafficInfoComparerMode.None:
					return 0;
				case IpTrafficInfoComparerMode.BySourceAddress:
					return CompareSourceAddress(x.Key, y.Key);
				case IpTrafficInfoComparerMode.ByNumPackets:
					return CompareByNumPackets(x.Value, y.Value);
				case IpTrafficInfoComparerMode.ByThroughput:
					return x.Value.BytesPerSecond.CompareTo(y.Value.BytesPerSecond) / -1;
				default:
					throw new NotImplementedException(ComparisionMode.ToString());
			}
        }

		private int CompareByNumPackets(IpPerformanceInfo x, IpPerformanceInfo y)
		{
            int realValue = x.TotalPackets.CompareTo(y.TotalPackets) / -1;
			if (realValue != 0)
				return realValue;
			return x.TotalBytes.CompareTo(y.TotalBytes);
        }

        private int CompareSourceAddress(IpTrafficInfo x, IpTrafficInfo y)
        {
			int cmp = 0;
			byte[] l = x.Source.GetAddressBytes();
			byte[] r = y.Source.GetAddressBytes();
			for (int i = 0; i < l.Length; i++)
			{
				cmp = l[i].CompareTo(r[i]);
				if (cmp != 0)
					return cmp;
			}

			l = x.Target.GetAddressBytes();
			r = y.Target.GetAddressBytes();
			for (int i = 0; i < l.Length; i++)
			{
				cmp = l[i].CompareTo(r[i]);
				if (cmp != 0)
					return cmp;
			}

			return x.Protocol.CompareTo(y.Protocol);
		}
    }

    public enum IpTrafficInfoComparerMode
    {
        None = 0,
        BySourceAddress = 1,
		ByNumPackets = 2,
		ByThroughput = 3
    }
}
