using System;
using System.Threading;

using DarkStrideToolbox;



using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;


namespace DarkStrideToolbox
{
	public class IDBuoyUpdateThread
	{
		#region Properties
		private User m_oConnectTo = null;
		private IdentificationBuoy m_oBuoy = null;
		private Thread m_oUpdateNetworkTieIn = null;
		private bool m_bUpdateDone = false;
		private bool m_bConnectedSuccessfully = false;
		public string m_sFailureMessage = "";
		#endregion


		public IDBuoyUpdateThread( IdentificationBuoy oBuoy,User oConnectTo )
		{
			m_oConnectTo = oConnectTo;
			m_oBuoy = oBuoy;

			m_oUpdateNetworkTieIn = new Thread(new ThreadStart(this.UpdateNetworkTieIn));
			m_oUpdateNetworkTieIn.IsBackground = true;
			m_oUpdateNetworkTieIn.Start();		
		}

		private void UpdateNetworkTieIn()
		{
			IdentificationBuoy oBuoy = null;
			

			//Try to connect to the user
			try
			{
				//Update that we tried to connect to them
				m_oConnectTo.TimeILastTriedToConnectedToThem = DateTime.Now;

				oBuoy = (IdentificationBuoy)Activator.GetObject( typeof(IdentificationBuoy),
							"tcp://" + m_oConnectTo.IP + ":" + m_oConnectTo.Port.ToString() + "/IdentificationBuoy" );
				//Give them ours
				oBuoy.UpdateUserList( m_oBuoy.Users,m_oBuoy.MyUser );
				//Here are that users users
				m_oBuoy.UpdateUserList( oBuoy.Users,m_oConnectTo );

				//Close down the connection
				oBuoy = null;
				//Success!
				m_bConnectedSuccessfully = true;
				m_oConnectTo.Status = enumStatus.Online;
			}
			catch( System.Exception oEx )
			{
				m_sFailureMessage = oEx.Message;
				if( oEx.Message == "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond" ||
					oEx.Message	== "No connection could be made because the target machine actively refused it" ||
					oEx.Message	== "Thread was being aborted."||
					oEx.Message == "Underlying socket was closed." ||
					oEx.Message == "An existing connection was forcibly closed by the remote host" )
				{
					//Failure
					m_oConnectTo.Status = enumStatus.Offline;
					m_oConnectTo.TimeOfLatestInfo = DateTime.Now;
				}
				else
				{
					m_bUpdateDone = true;
					throw new System.Exception( "IDBuoyUpdateThread Failed.",oEx );
				}
			}

			m_bUpdateDone = true;
		}


		public void Dispose()
		{
			m_oUpdateNetworkTieIn.Abort();
			m_oUpdateNetworkTieIn = null;
		}



		#region Properties
		public bool UpdateDone
		{
			get
			{
				return( m_bUpdateDone );
			}
		}
		public bool ConnectedSuccessfully
		{
			get
			{
				return( m_bConnectedSuccessfully );
			}
		}
		public User ConnectTo
		{
			get
			{
				return( m_oConnectTo );
			}
		}
		public string FailureMessage
		{
			get
			{
				return( m_sFailureMessage );
			}
			set
			{
				m_sFailureMessage = value;
			}
		}
		#endregion
	}
}
