﻿using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Trinity.Unit.Tests
{
	[TestClass]
	public class UT_Culture
	{
		[TestMethod]
		[NotReRunnable]
		public void All_Tests_Cultures()
		{
			// get all tests in the unit test project assembly
			var testClasses = (from t in typeof(NotReRunnableAttribute).GetTypeInfo().Assembly.DefinedTypes
				where t.GetCustomAttribute<TestClassAttribute>() != null
				select new
				{
					Constructor = t.GetConstructor(new Type[] { }),
					ClassInit = t.GetMethods().SingleOrDefault(m => m.GetCustomAttribute<ClassInitializeAttribute>() != null),
					TestInit = t.GetMethods().SingleOrDefault(m => m.GetCustomAttribute<TestInitializeAttribute>() != null),
					TestCleanup = t.GetMethods().SingleOrDefault(m => m.GetCustomAttribute<TestCleanupAttribute>() != null),
					ClassCleanup = t.GetMethods().SingleOrDefault(m => m.GetCustomAttribute<ClassCleanupAttribute>() != null),
					TestMethods = t.GetMethods().Where(m =>
							m.GetCustomAttribute<TestMethodAttribute>() != null && m.GetCustomAttribute<NotReRunnableAttribute>() == null)
						.ToList()
				}).ToList();

			var cultures = new[] {"zh-CN", "de-DE", "ko-KR", "ja-JP", "en-US" };
			var originalUICulture = CultureInfo.CurrentCulture;
			var emtpyObjArray = new object[] { };
			Console.WriteLine("ORIG: " + CultureInfo.CurrentCulture);
			// run all the tests, varying the culture each time.
			try
			{
				foreach (var culture in cultures)
				{
					CultureInfo.CurrentCulture = new CultureInfo(culture);
					Console.WriteLine(CultureInfo.CurrentCulture);
					foreach (var c in testClasses)
					{
						var instance = c.Constructor.Invoke(emtpyObjArray);
						if (c.ClassInit != null)
						{
							c.ClassInit.Invoke(instance, emtpyObjArray);
						}
						foreach (var m in c.TestMethods)
						{
							if (c.TestInit != null)
							{
								c.TestInit.Invoke(instance, emtpyObjArray);
							}
							m.Invoke(instance, emtpyObjArray);
							if (c.TestCleanup != null)
							{
								c.TestCleanup.Invoke(instance, emtpyObjArray);
							}
						}
						if (c.ClassCleanup != null)
						{
							c.ClassCleanup.Invoke(instance, emtpyObjArray);
						}
					}
				}
			}
			finally
			{
				CultureInfo.CurrentCulture = originalUICulture;
			}
		}
	}

	public class NotReRunnableAttribute : Attribute
	{
	}
}