using System;
using NUnit.Framework;

namespace Orciid.Core.Util
{
	/// <summary>
	/// Test class
	/// </summary>
	/// <remarks>
	/// Test cases
	/// </remarks>
	[TestFixture]
	public class TestIntegerListTools
	{
		/// <summary>
		/// Test
		/// </summary>
		[Test]
		public void TestIntersect()
		{
			int[] a = new int[] { 1, 5, 3, 2, 4 };
			int[] b = new int[] { 8, 7, 6, 4, 5 };
			int[] c = new int[] { 9, 6, 8, 7 };

			Assert.IsNull(IntegerListTools.Intersect(null, null));
			Assert.IsNull(IntegerListTools.Intersect(a, null));
			Assert.IsNull(IntegerListTools.Intersect(null, a));

			Assert.IsNull(IntegerListTools.Intersect(a, c));

			CompareArrays(a, IntegerListTools.Intersect(a, a));
			
			CompareArrays(new int[] { 4, 5 }, IntegerListTools.Intersect(a, b));
		}

        /// <summary>
        /// Test
        /// </summary>
        /// <remarks>
        /// Test
        /// </remarks>
		[Test]
		public void TestIntersectWithDuplicates()
		{
			int[] a = new int[] { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5 };
			int[] b = new int[] { 2, 3, 3, 4, 4, 4 };
			
			CompareArrays(new int[] { 2, 3, 3, 4, 4, 4 }, IntegerListTools.Intersect(a, b));
		}

        /// <summary>
        /// Test
        /// </summary>
        /// <remarks>
        /// Test
        /// </remarks>
        [Test]
		public void TestPerformance()
		{
			const int NUM = 1000000;
			int[] a = new int[NUM];
			int[] b = new int[NUM];
			for (int i = 0; i < NUM; i++)
			{
				a[i] = i;
				b[i] = i + NUM / 2;
			}

			DateTime start = DateTime.Now;
			int[] c = IntegerListTools.Intersect(a, b);
			TimeSpan duration = DateTime.Now - start;
			Console.WriteLine("Intersect with {0} elements took {1} ms",
				NUM, duration.Milliseconds);
			
			Assert.AreEqual(NUM / 2, c.Length);
		}

		private static void CompareArrays(int[] a, int[] b)
		{
			Array.Sort(a);
			Array.Sort(b);
			Assert.AreEqual(a, b);
		}
	}
}
