using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using NU.OJL.MPRTOS.TLV.Base;
using NU.OJL.MPRTOS.TLV.Core.Controls;

namespace NU.OJL.MPRTOS.TLV.Core.Commands
{
	public class Sample1Command : ICommand
	{
		private OpenFileDialog _ofd = new OpenFileDialog();
		private string _Text;

		public Sample1Command()
		{
			Text = "シミュレーション環境を開く";
		}

		public string Text
		{
			get { return _Text; }
			set { _Text = value; }
		}

		public bool CanUndo { get { return false; } set { } }

		public void Do()
		{
			if (_ofd.ShowDialog() == DialogResult.OK)
			{
				CreateFileContext(_ofd.FileName);
			}
		}

		public void Undo()
		{

		}

		private IFileContext CreateFileContext(string name)
		{
			IFileContext fileContext;
			Form view;

			CreateSimFileContextView(name, out fileContext, out view);

			view.Name = name + "_" + view.GetHashCode().ToString("x");

			ApplicationFactory.SetFileContext(fileContext, view);

			return fileContext;
		}

		private static bool CreateSimFileContextView(string name, out IFileContext fileContext, out Form view)
		{
			Assembly assembly;

			try
			{
				assembly = Assembly.LoadFrom(name);
			}
			catch (FileLoadException)
			{
				fileContext = null;
				view = null;

				return false;
			}

			IEnvironment env = LoadEnvironmnt(assembly);

			EnvironmentFileContext simContext = new EnvironmentFileContext(env);

			simContext.Prepare();

			fileContext = simContext;

			view = new TraceLogDisplayPanel();
			view.Text = Path.GetFileNameWithoutExtension(name);

			return true;
		}

		private static IEnvironment LoadEnvironmnt(Assembly assembly)
		{
			Type[] types = assembly.GetTypes();
			foreach (Type type in types)
			{
				Type[] ifs = type.GetInterfaces();
				foreach (Type i in ifs)
				{
					if (i == typeof(IEnvironment))
					{
						ConstructorInfo info = type.GetConstructor(new Type[] { typeof(CommandManager), typeof(IWindowManager) });
						if (info == null)
							continue;

						return (IEnvironment)info.Invoke(new object[] { ApplicationFactory.CommandManager, ApplicationFactory.WindowManager });
					}
				}
			}

			return null;
		}
	}
}
