using System;
using System.Diagnostics;
using Medivators.Common.Settings;

namespace Medivators.Common.Logging
{
	/// <summary>
	/// Summary description for ApplicationLog.
	/// </summary>
	public class ApplicationLog : ILogProvider
	{
		private string		_sourceName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
		private bool		_init		= false;
		private EventLog	_log		= null;
		
		#region construct/init/dispose
		
		public void Initialize()
		{
			if ( ! _init )
			{
				//	insure log source has been created and registered on the local host
				if ( ! EventLog.SourceExists(this._sourceName) )
				{
					EventLog.CreateEventSource(this._sourceName, null);
					//	will not be able to access source in this session. Newly
					//	created sources require the OS to do stuff that will not
					//	happen until the next session
					return;
				}
				this._log  = new EventLog();
				this._log.Source = this._sourceName;
				this._init = true;
			}
		}	

		public void Dispose()
		{
			if ( this._log != null )
				this._log.Dispose();
		}

		#endregion

		public string SourceName
		{
			get { return this._sourceName;  }
			set { this._sourceName = value; }
		}

		#region ILogProvider methods

		public bool WriteLog ( string Text )
		{
			return this.WriteLog(Text, EventLogEntryType.Information, null);
		}
		public bool WriteLog ( string Text, EventLogEntryType LogEntryType )
		{
			return this.WriteLog( Text, LogEntryType , null );
		}
		public bool WriteLog(string Text, EventLogEntryType LogEntryType, byte[] Data)
		{
			try
			{
				if (!_init)
					this.Initialize();
				this._log.WriteEntry(Text, LogEntryType, 0, 0, Data);
				return true;
			}
			catch
			{
				return false;
			}
		}
		public bool WriteLog(Medivators.Common.Enums.LogEntryType Criticality, string Text)
		{
			return this.WriteLog(Criticality, Text, EventLogEntryType.Information, null);
		}
		public bool WriteLog(Medivators.Common.Enums.LogEntryType Criticality, string Text, EventLogEntryType LogType)
		{
			return this.WriteLog(Criticality, Text, LogType, null);
		}
		public bool WriteLog(Medivators.Common.Enums.LogEntryType Criticality, string Text, EventLogEntryType LogType, byte[] Data)
		{
			bool rtnVal = true;
			byte EntryValue = Convert.ToByte(Criticality);
			byte LogValue = Convert.ToByte(TextSettings.GetInstance()[Medivators.Common.Enums.SettingTypes.Application, "LoggingLevel"]);
			if (EntryValue > LogValue || LogValue == 0)
				rtnVal = false;
			else
				rtnVal = this.WriteLog(Text, LogType, Data);
			return rtnVal;
		}

		#endregion
	}
}
