using System.Reflection;

namespace skyscraper8.AnagramViewer
{
	internal static class Program
	{
		/// <summary>
		///  The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			// To customize application configuration such as set high DPI settings or default font,
			// see https://aka.ms/applicationconfiguration.
			ApplicationConfiguration.Initialize();

			if (args.Length == 0)
			{
				MessageBox.Show("Invalid function call!");
				return;
			}

			FileInfo fi = new FileInfo(args[0]);
			if (!fi.Exists)
			{
				MessageBox.Show("Couldn't find {0}!", args[0]);
				return;
			}

			FileStream fileStream = fi.OpenRead();
			BufferedStream bufferedStream = new BufferedStream(fileStream, 2048);

			IFileTypeHandler usableHandler = null;
			DataType determiendDataType = DataType.Unknown;
			Type fileHandlerType = typeof(IFileTypeHandler);
			Assembly assembly = fileHandlerType.Assembly;
			Type[] types = assembly.GetTypes();
			foreach (Type typeCandidate in types)
			{
				if (!typeCandidate.IsAssignableTo(fileHandlerType))
					continue;

				if (typeCandidate.IsInterface)
					continue;

				bufferedStream.Position = 0;
				IFileTypeHandler instance = (IFileTypeHandler)Activator.CreateInstance(typeCandidate);
				DataType checkDataType = instance.CheckDataType(bufferedStream);
				if (checkDataType != DataType.Unknown)
				{
					usableHandler = instance;
					determiendDataType = checkDataType;
					bufferedStream.Position = 0;
					break;
				}
			}

			if (usableHandler == null)
			{
				MessageBox.Show(String.Format("Don't know what type of file {0} is.", fi.FullName));
				return;
			}

			Form finalForm = null;
			switch (determiendDataType)
			{
				case DataType.Image:
					Image asImage = usableHandler.AsImage(bufferedStream);
					finalForm = new ImageViewer(asImage);
					break;
				default:
					MessageBox.Show(String.Format("Don't know how to handle files of type {0}", determiendDataType.ToString()));
					return;
			}

			finalForm.Text = String.Format("Anagram Viewer - [{0}]", fi.Name);
			Application.Run(finalForm);
		}
	}
}