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;
		#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 );
				//Here are that users users
				m_oBuoy.UpdateUserList( oBuoy.Users );
				//Close down the connection
				oBuoy = null;
				//Success!
				m_bConnectedSuccessfully = true;
			}
			catch( System.Exception oEx )
			{
				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."	)
				{
					//Failure
					m_oConnectTo.Status = enumStatus.Unavailable;
				}
				else
				{
					m_bUpdateDone = true;
					throw new System.Exception( "IDBuoyUpdateThread Failed.",oEx );
				}
			}
			m_oConnectTo.TimeOfLatestInfo = DateTime.Now;

			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 );
			}
		}
		#endregion
	}
}
