using System;
using Medivators.Common.Logging;
using Medivators.Common;
using Medivators.Common.Enums;

namespace Medivators.Common
{
	/// <summary>
	/// Summary description for ErrorHandler.
	/// </summary>
	public class ErrorHandler : IDisposable
	{
		private static ErrorHandler		_instance;
		private ILogProvider			_primaryErrorLog = null;
		private ILogProvider			_backupErrorLog = null;

		#region construct/init/dispose

		private ErrorHandler()
		{
		}

		public static ErrorHandler GetInstance()
		{
			if ( _instance == null )
				_instance = new ErrorHandler();
			return (ErrorHandler)_instance;
		}
		public void Initialize ( ILogProvider PrimaryErrorLog, ILogProvider SecondaryErrorLog )
		{
			this._primaryErrorLog = PrimaryErrorLog;
			this._backupErrorLog = SecondaryErrorLog;
		}
		public void Dispose()
		{
			this._primaryErrorLog.Dispose();
			this._backupErrorLog.Dispose();
		}
		
		#endregion

		#region exception logging

		#region *	log writing only 
		public void LogException ( Exception ex )
		{
			this.LogException ( LogEntryType.Critical, ex.ToString() );
		}
		public void LogException ( string Message, Exception ex )
		{
			this.LogException( LogEntryType.Critical, Message + Constants.NewLine + ex.ToString());
		}
		public void LogException(string Message)
		{
			this.LogException(LogEntryType.Critical, Message);
		}
		public void LogException(LogEntryType Criticality, string Message)
		{
			bool Success = true;
			try
			{
				this._primaryErrorLog.WriteLog ( Criticality, Message, System.Diagnostics.EventLogEntryType.Error );
			}
			catch 
			{
				Success = false;
			}
			if ( ! Success )
			{
				try
				{
					this._backupErrorLog.WriteLog(Criticality, Message, System.Diagnostics.EventLogEntryType.Error);
				}
				catch
				{
					//  if no logs seem to be working, they may not be initialized.
					//	try to get something into the event log
					Log.GetInstance().WriteLog(Message,true);
				}
			}
		}
		#endregion 

		#region *	logwriting + user prompt

		public void LogException ( bool ShowUser, Exception ex )
		{
			this.LogException ( ex);
			if ( ShowUser ) this.ShowUser(ex.ToString());
		}
		public void LogException ( bool ShowUser, string Message, Exception ex )
		{
			this.LogException ( Message, ex );
			if ( ShowUser ) this.ShowUser(Message + Constants.NewLine + ex.ToString());
		}
		public void LogException ( bool ShowUser, string Message )
		{
			this.LogException ( Message );
			if ( ShowUser ) this.ShowUser(Message);
		}
		#endregion
		
		#endregion 

		private void ShowUser ( string Message )
		{
			MsgBox.Show( Message, System.Windows.Forms.MessageBoxIcon.Exclamation );
		}

	}
}
