using System;
using System.Collections.Generic;

using System.Text;
using System.Threading;

namespace StarTrinity
{

	static class SingleInstanceUtility
	{
		public static bool IsItASingleInstance(String appName, Action secondInstanceCallback)
		{
			EventWaitHandle eventWaitHandle = null;
			String eventName = Environment.MachineName + "-" + Environment.CurrentDirectory.Replace('\\', '-') + "-" + appName;

			bool isSingleInstance = false;

			try
			{
				eventWaitHandle = EventWaitHandle.OpenExisting(eventName);
			}
			catch
			{
				// it's first instance
				isSingleInstance = true;
			}

			if (isSingleInstance)
			{
				eventWaitHandle = new EventWaitHandle(
					false,
					EventResetMode.AutoReset,
					eventName);

				ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, waitOrTimerCallback, secondInstanceCallback, Timeout.Infinite, false);

				// not need more
				eventWaitHandle.Close();
			}
			else
			{
				eventWaitHandle.Set();
				//Environment.Exit(0);
			}

			return isSingleInstance;
		}
		private static void waitOrTimerCallback(Object state, Boolean timedOut)
		{
			try
			{
				Action secondInstanceCallback = (Action)state;
				secondInstanceCallback();
			}
			catch
			{
			}
		}
	}

}
