﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Indigo
{
	public class Server
	{
		private Protocol mvarProtocol = null;
		public Protocol Protocol { get { return mvarProtocol; } set { mvarProtocol = value; } }

		private Service mvarService = null;
		public Service Service { get { return mvarService; } set { mvarService = value; } }

		private Transport mvarTransport = null;
		public Transport Transport { get { return mvarTransport; } set { mvarTransport = value; } }

		private ServerImplementation mvarImplementation = null;

		private System.Threading.Thread _t = null;

		public void Start()
		{
			mvarImplementation = mvarTransport.GetServerImplementation();

			if (_t == null) _t = new System.Threading.Thread(t_ThreadStart);
			if (!_t.IsAlive)
			{
				_t.Name = "Indigo Server Thread";
				_t.Start();
			}
		}

		public void Stop()
		{
			if (_t != null && _t.IsAlive) _t.Abort();
			_t = null;
		}

		private System.Collections.Generic.Dictionary<Client, System.Threading.Thread> clientThreads = new Dictionary<Client, System.Threading.Thread>();

		private void tClient_ParameterizedThreadStart(object data)
		{
			Client client = (data as Client);
			OnClientConnected(new ClientConnectedEventArgs(client));
		}

		public event ClientConnectedEventHandler ClientConnected;
		protected virtual void OnClientConnected(ClientConnectedEventArgs e)
		{
			if (ClientConnected != null) ClientConnected(this, e);
		}

		private void t_ThreadStart()
		{
			mvarImplementation.Initialize();

			while (true)
			{
				Client client = mvarImplementation.WaitForClient();
				if (client != null)
				{
					System.Threading.Thread tClient = new System.Threading.Thread(tClient_ParameterizedThreadStart);
					clientThreads.Add(client, tClient);
					clientThreads[client].Start(client);
				}
				System.Threading.Thread.Sleep(500);
			}
		}
	}
}
