using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

using EA.GameTalk;
using EA.GameTalkMessages;
//using EA.GameTalk.GameTalkManager;

namespace EA.FileTalk
{
	public partial class FileTalkConsole : Form
	{
		private FileServer mFileServer;
		private TraceLogger mTraceLogger = new TraceLogger();

		public FileTalkConsole()
		{
			InitializeComponent();

			// Useful for debugging - allows us to look at log file if issue arises
			mTraceLogger.mLogDelegate = new LogDelegate(Log);
			Trace.Listeners.Add(mTraceLogger);

			//this.textBox1.AppendText("testing");
			mFileServer = new FileServer();
			mFileServer.StartServer();
		}

		private void FileTalkConsole_FormClosed(object sender, FormClosedEventArgs e)
		{
			mFileServer.StopServer();
			Trace.Listeners.Remove(mTraceLogger);
			mTraceLogger.Close();
		}

		// This delegate enables asynchronous calls for setting the Text property on a TextBox control.
		public delegate void LogDelegate(string logData);

		public void Log(string logData)
		{
			// InvokeRequired required compares the thread ID of the
			// calling thread to the thread ID of the creating thread.
			// If these threads are different, it returns true.
			if (this.textBox1.InvokeRequired)
			{
				LogDelegate d = new LogDelegate(Log);
				Invoke(d, new object[] { logData });
				return;
			}

			textBox1.AppendText(logData);
		}


		public class TraceLogger : TraceListener
		{
			public FileTalkConsole.LogDelegate mLogDelegate;
			
			public override void WriteLine(string text)
			{
				try
				{
					//mFileTalkConsole.Log(text + Environment.NewLine);
					mLogDelegate(text + Environment.NewLine);
				}
				catch
				{
					// Can't really log this if the error occurs in our logger :(
				}
			}

			public override void Write(string text)
			{
				try
				{
					//mFileTalkConsole.Log(text);
					mLogDelegate(text);
				}
				catch
				{
					// Can't really log this if the error occurs in our logger :(
				}
			}

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

}