using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using ExtensionMethods;

namespace Trigger
{
	static class Program
	{
		private static Mutex mutex = new Mutex(true, "{Trigger4Win-78F04E6BFF8E}");

		[DllImport("user32.dll")]
		[return: MarshalAs(UnmanagedType.Bool)]
		private static extern bool SetForegroundWindow(IntPtr hWnd);

		/// <summary>
		/// Der Haupteinstiegspunkt für die Anwendung.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			Options options = new Options();
			if (!CommandLine.Parser.Default.ParseArguments(Environment.GetCommandLineArgs(), options))
				Environment.Exit(CommandLine.Parser.DefaultExitCodeFail);

			try
			{
				if (mutex.WaitOne(TimeSpan.Zero, true))
					show(options, mutex);
				else
				{
					IntPtr hWnd = Actions.System.FindWindow(null, "Trigger4Win");
					if (options.Admin)
					{
						Actions.System.SendMessage(hWnd, Classes.System.WindowsMessages.WM_USER, IntPtr.Zero, new IntPtr(-1));
						// shall we check for the mutex here again? This throws an AbandonedMutexException
						show(options, mutex);
					}
					else if (options.Trigger.IsNotEmpty())
						Actions.System.PostMessage(hWnd, Classes.System.WindowsMessages.WM_USER, new IntPtr(options.Trigger.GetHashCode()), IntPtr.Zero);
				}
			}
			catch (AbandonedMutexException e)
			{
				MessageBox.Show(e.Message + "\n\n" + e.StackTrace);
				throw;
			}
		}

		static void show(Options options, Mutex mutex)
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new Main(options));
			mutex.ReleaseMutex();
		}
	}
}
