using System;
using System.Diagnostics;
using System.IO;
using Minntech.Common;

namespace Minntech.Logging
{
	/// <summary>
	/// Summary description for TextLog.
	/// </summary>
	public class TextLog : ILogProvider
	{
		private StreamWriter	_file = null;
		private string			_path = string.Empty;

		#region construct/init/dispose
		public TextLog()
		{
		}
		public TextLog( string FilePath )
		{
			this._path = FilePath;
		}
		public void Dispose()
		{
			if ( this._file != null )
			{
				this._file.Flush();
				this._file.Close();
			}
		}
		#endregion

		#region ILogProvider Members

		public void Initialize()
		{
			try 
			{
				// validate file path
				if ( ! Directory.Exists(Path.GetDirectoryName(this._path) ) )
					throw new DirectoryNotFoundException("File Path " + this._path + " does not exist or is inaccessible");

				//	if logfile already exists, scrap it
				if ( File.Exists ( this._path ) )
				{
					File.SetAttributes(this._path, FileAttributes.Normal);
					File.Delete(this._path);
				}
			}
			catch ( Exception ex )
			{
				ErrorHandler.GetInstance().LogException("TextLog.Initialize", ex);
			}
		}

		public void WriteLog(string Text)
		{
			this.WriteLog(Text, EventLogEntryType.Information, null );
		}

		public void WriteLog(string Text, System.Diagnostics.EventLogEntryType LogType)
		{
			this.WriteLog(Text, LogType, null );
		}

		public void WriteLog(string Text, System.Diagnostics.EventLogEntryType LogType, byte[] Data)
		{
			//	prepare the log line
			string logLine = DateTime.Now.ToString();
			logLine += Text;
			logLine += LogType.ToString();
			if ( Data != null )
			{
				foreach ( byte chr in Data )
				{
					logLine += chr.ToString();
				}
			}

			//	 flush anything pending from previous calls
			if ( this._file != null )
			{
				this._file.Flush();
				this._file.Close();
			}
			this._file = new StreamWriter(this._path, true);
			this._file.WriteLine ( logLine );
		}

		#endregion

		public string LogfilePath 
		{
			get { return this._path; }
			set { this._path = value; }
		}
	}
}
