using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Threading;
using System.Text;

namespace EA.GameTalkServer
{
	/// <summary>
	/// Summary description for TextBoxTraceListener.
	/// </summary>
	public class TextBoxTraceListener : TraceListener
	{
		// Create a UI context variable
		private static SynchronizationContext mUISynchronizationContext = null;
		private TextBox mTextBox;

		private System.Timers.Timer mReadFromBufferTimer;
		private StringBuilder mBufferedText = new StringBuilder();

		public TextBoxTraceListener(TextBox textBox)
		{
			// Assign a windows forms syncronization context because we do this 
			// in the creating thread, we can create a handle to this thread for 
			// the life of the UI control
			mUISynchronizationContext = WindowsFormsSynchronizationContext.Current;

			mTextBox = textBox;

			mReadFromBufferTimer = new System.Timers.Timer(10);
			mReadFromBufferTimer.Elapsed += new System.Timers.ElapsedEventHandler(UpdateUi);
			// Setting AutoReset to false is one way to prevent the timer's callback from being reinvoked while it is currently executing
			mReadFromBufferTimer.AutoReset = false;
			mReadFromBufferTimer.Enabled = true;
		}

		private void UpdateUi(object sender, System.Timers.ElapsedEventArgs args)
		{
			mUISynchronizationContext.Send(new SendOrPostCallback(
				delegate(object state)
				{
					if (mTextBox.Text.Length == mTextBox.MaxLength)
						mTextBox.Clear();
					lock (mBufferedText)
					{
						mTextBox.AppendText(mBufferedText.ToString());
						mBufferedText.Clear();
					}
				}
			), null);
		}

		public override void Write (string message)
		{
			lock (mBufferedText)
			{
				mBufferedText.Append(message);
			}
		}

		public override void WriteLine(string message)
		{
			lock (mBufferedText)
			{
				mBufferedText.Append(message + Environment.NewLine);
			}
		}


	}
}
