using skyscraper5.UI.StreamAcquisition;
using System.Reflection;

namespace skyscraper5.UI
{
    internal static class Program
    {
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            List<StreamAcquirerListItem> streamAcquirers;
			Assembly assembly = Assembly.GetExecutingAssembly();
            streamAcquirers = assembly.GetTypes()
                .Where(t => typeof(IStreamAcquirer).IsAssignableFrom(t))
                .Where(t => !t.IsInterface)
                .Where(t => !t.IsAbstract)
                .Select(x => x.GetConstructor(Type.EmptyTypes))
                .Select(x => x.Invoke(new object[0]))
                .Select(x => new StreamAcquirerListItem((IStreamAcquirer)x))
                .ToList();

            StreamSource acquiredStream = null;
			string[] args = Environment.GetCommandLineArgs();
            if (args.Length == 2)
            {
                foreach (StreamAcquirerListItem possibleStreamer in streamAcquirers)
                {
                    object handle = possibleStreamer.Wrapped.BaseGetHandle(args[1]);
                    if (handle == null)
                        continue;
					StreamSource stream = possibleStreamer.Wrapped.BaseGetStream(handle);
                    if (stream == null)
                        continue;
                    acquiredStream = stream;
                    break;
                }
            }


			ApplicationConfiguration.Initialize();
			if (acquiredStream == null)
			{
                StreamAcquirerPickingForm pickingForm = new StreamAcquirerPickingForm(streamAcquirers,args);
                pickingForm.ShowDialog();
                if (pickingForm.StreamSource == null)
                    return;
                acquiredStream = pickingForm.StreamSource;
			}

			Application.Run(new Form1(acquiredStream));
        }
    }
}