using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
using System.Threading;

using Microsoft.Win32;

using EA.GameTalkMessages;

namespace EA.GameTalkServer
{
	class GameTalkConfigReader : EA.GameTalkRouter.ConfigReader
	{
		private System.Timers.Timer mTimer;
		// Prevents multiple threads from executing the same timer elapsed event handler
		private static int mSyncPoint = 0;

		private GameTalkConfigReader()
		{
			mCreateFileForMonitorToDelete = true;
			mTimer = new System.Timers.Timer(1000);
			this.mTimer.Elapsed += new ElapsedEventHandler(ReadServerConfig);
			mTimer.Enabled = true;
		}

		~GameTalkConfigReader()
		{
			mTimer.Enabled = false;
		}

		#region Singleton code
		public static EA.GameTalkRouter.ConfigReader Singleton
		{
			get
			{
				return Nested.instance;
			}
		}

		class Nested
		{
			// Explicit static constructor to tell C# compiler not to mark type as beforefieldinit
			static Nested()
			{
			}

			internal static readonly GameTalkConfigReader instance = new GameTalkConfigReader();
		}
		#endregion

		protected void ReadServerConfig()
		{
			RegistryKey gameTalkConfigRegistryKey = null;
			try
			{
				mLoggingLevel = Configuration.Instance.GetLoggingLevel();

				mLimitLogFileSize = Configuration.Instance.LimitLogFileSize();
			}
			catch
			{
			}
			finally
			{
				if (gameTalkConfigRegistryKey != null)
					gameTalkConfigRegistryKey.Close();
			}
		}

		private void ReadServerConfig(object source, ElapsedEventArgs e)
		{
			int sync = Interlocked.CompareExchange(ref mSyncPoint, 1, 0);
			if (sync != 0)
				return;

			try
			{
				mTimer.Stop();
				ReadServerConfig();
				mTimer.Start();
			}
			catch { }
			finally
			{
				mSyncPoint = 0;
			}
		}
	}
}
