// (c) 2005 Electronic Arts Inc.
//

using System;
using System.Diagnostics;
using System.IO;
using System.Xml;

namespace EA.FileTalk
{
	/// <summary>
	/// Summary description for Logger.
	/// </summary>
	public class LogManager : TraceListener
	{
		private const long MAX_LOG_FILE_SIZE = 1024 * 1024 * 50;
		private XmlTextWriter mWriter = null;
		//Format date such that it is acceptable to the windows file system
		private readonly string mLoggingFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"GameTalkServer\FileTalkServer.log");

		private void CreateWriterAndFile()
		{
			//String dateStringFormatted = DateTime.Now.ToString("[dd-MMMM-yyyy]hh-mm-ss");
			try
			{
				FileStream fileStream = new FileStream(mLoggingFile, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
				// Create the writer
				mWriter = new XmlTextWriter(fileStream, System.Text.Encoding.UTF8);

				mWriter.Formatting = Formatting.Indented;
				mWriter.IndentChar = '\t';
				mWriter.Indentation = 1;

				// Begin the document
				mWriter.WriteStartDocument();

				mWriter.WriteStartElement("Logging");
			}
			catch
			{
				// Can't really log this if the error occurs in our logger :(
			}
		}

		public override void WriteLine(string text)
		{
			try
			{
				// Since this is called so frequently we may want to consider allowing multiple concurrent
				// writes to the log files instead of potentially blocking at this point
				if (mWriter == null)
				{
					CreateWriterAndFile();
				}
				else
				{
					FileInfo fileInfo = new FileInfo(mLoggingFile);
					if (fileInfo.Length > MAX_LOG_FILE_SIZE)
					{
						mWriter.Close();
						CreateWriterAndFile();
					}
				}

				mWriter.WriteStartElement("LogEntry");
				mWriter.WriteAttributeString("time", DateTime.Now.ToString());
				mWriter.WriteString(text);
				mWriter.WriteEndElement();
				mWriter.Flush();
			}
			catch
			{
				// Can't really log this if the error occurs in our logger :(
			}
		}

		public override void Write(string text)
		{
			WriteLine(text);
		}

		override public void Close()
		{
			mWriter.WriteEndElement();
			mWriter.Close();
			base.Close();
		}
	}
}
