using System;
using System.Windows.Forms;
using Habanero.BO;
using Habanero.Faces.Base;
using Habanero.Faces.Win;
using Habanero.Base;
using log4net;
using log4net.Config;
using <<BOPROJECT_NAME>>;

namespace <<NAMESPACE>>
{
	static class Program
	{
		private static readonly ILog log = LogManager.GetLogger(typeof(Program));

		[STAThread]
		static void Main()
		{
			GlobalRegistry.ApplicationName = "<<APPLICATION_NAME>>";
			GlobalRegistry.ApplicationVersion = "<<PROJECT_VERSION>>";
			HabaneroAppWin mainApp = new HabaneroAppWin(GlobalRegistry.ApplicationName, GlobalRegistry.ApplicationVersion);
			mainApp.ClassDefsXml = BOBroker.GetClassDefsXml();
			try
			{
				log.Debug(string.Format("-------- {0} {1} Starting  ---------", GlobalRegistry.ApplicationName, GlobalRegistry.ApplicationVersion));
				if (!mainApp.Startup()) return;
                // Uncomment the next line of code to use an "In Memory" data accessor (instead of your Database).
                //BORegistry.DataAccessor = new DataAccessorInMemory();
			}
			catch (Exception ex)
			{
				log.Error(ex.Message);
			}

			try
			{
				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault(false);

				FormWin programForm = new FormWin();
				SetupMainForm(programForm);
				Application.Run(programForm);
			}
			catch (Exception ex)
			{
				GlobalRegistry.UIExceptionNotifier.Notify(ex,
						"An error has occurred in the application.",
						"Application Error");
			}
		}

		public static void SetupMainForm(IFormHabanero programForm)
		{
			IMainMenuHabanero mainMenuHabanero = SetupMainMenu(programForm, GlobalUIRegistry.ControlFactory, new MenuBuilderWin(GlobalUIRegistry.ControlFactory));
			mainMenuHabanero.DockInForm(programForm);
			programForm.Text = GlobalRegistry.ApplicationName + " " + GlobalRegistry.ApplicationVersion;
			programForm.WindowState = Habanero.Faces.Base.FormWindowState.Maximized;
		}        

		public static IMainMenuHabanero SetupMainMenu(IFormHabanero programForm, IControlFactory controlFactory, IMenuBuilder menuBuilder)
		{
			HabaneroMenu mainMenu = new HabaneroMenu("Main", programForm, GlobalUIRegistry.ControlFactory);

			HabaneroMenu currentMenu = mainMenu.AddSubMenu("&File");
			HabaneroMenu.Item currentMenuItem = currentMenu.AddMenuItem("E&xit");
			currentMenuItem.CustomHandler += delegate { programForm.Close(); };

			AddGeneratedFormsMenu(mainMenu, controlFactory);

			return menuBuilder.BuildMainMenu(mainMenu);
		}

		private static void AddGeneratedFormsMenu(HabaneroMenu menu, IControlFactory controlFactory)
		{
			HabaneroMenu dataMenu = menu.AddSubMenu("&Generated Forms");
			foreach (Type type in typeof (Program).Assembly.GetTypes())
			{
				if (!type.IsSubclassOf(typeof (MenuItemCreator))) continue;
				MenuItemCreator menuItemCreator = (MenuItemCreator) Activator.CreateInstance(type, new object[] {});
				menuItemCreator.AddToMenu(dataMenu, controlFactory);
			}
		}
	}
}