using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
using vclass.chat.server;
using System.Xml;
using vclass.chat.client;

namespace vclass.chat
{

	public class SocketHelper
	{
		//reference chat server
		private ChatServer chatserver;
		//reference chat client
		private TcpClient client;
		//nickname 
		private string nickname="";
		private string password = "";
		//room number 0 means no room assigned yet
		private int room=0;
		//data read from client
		private string readdata="";

		//action delegate
//		private SocketHelperAction action;

		//public properties
		public int Room
		{
			get{return room;}
		}

		public string Nickname
		{
			get{return nickname;}
		}

		//2 parameters Constructor
		public SocketHelper(ChatServer s,TcpClient c)
		{
			client=c;
			chatserver=s;
			Thread t=new Thread(new ThreadStart(HandleClient));
			t.Start();
		}


		//The main method that handle all the chat communication with the client
		private void HandleClient()
		{
	
				//Send connection message to client
				//returning the user id
	//			Console.WriteLine("message from server");
	//			chatserver.Write(client.GetStream(),"message from server");
				
				string responseData = chatserver.Read(client.GetStream());
	//			Console.WriteLine("server->handleClient:  "+responseData);
		
				XmlDocument login = new XmlDocument();
				login.LoadXml(responseData);
				//	Console.WriteLine("Client->response1: "+response[1].ToString());
				//	XmlElement root = doc.DocumentElement;
				XmlNode root = login.FirstChild;
				
				if(root.HasChildNodes)
				{
					nickname = root["username"].InnerText;
					Console.WriteLine("username: "+nickname);
					password = root["password"].InnerText;
					Console.WriteLine("password: "+password);
				}

				
	/*	
	 		//buffer
				byte[] bytes= new byte[256];

				//set nickname as user id which is alraedy unique
				nickname=auth.UserID;
*/
				//Assign a room to connected client
				room=chatserver.AssignRoom(nickname);
				Console.WriteLine("room assigned= "+room + " for " + nickname);

				//Add to Connections
				try
				{
					chatserver.AddConnection(nickname,client);
				}
				catch{}
				//Populate the other users to the new established connection
				string roomUsers = "";
				roomUsers += "<command><allUsers>";
				foreach(string  s in chatserver.RoomUsers[room-1].Keys)
					roomUsers += "<username>"+s+"</username>";
				roomUsers += "</allUsers></command>";
				chatserver.Write(client.GetStream(),roomUsers);
				Console.WriteLine(roomUsers);

	//			chatserver.Write(client.GetStream(),"selam");

				//Broadcast to chat room about the new user
				chatserver.Broadcast("<command><newuser><username>"+nickname+"</username></newuser></command>",room);

				//listen to all client data send
				while((readdata=chatserver.Read(client.GetStream()))!="")
				{
					readdata=readdata.Trim();

					//Print out read data in console
					// Broadcasts
					// 1 - messages from Chatpanel.SENDBUTTON
					//		1.1 <to>Public</to>
					//		1.2 <to>ismail</to>
					// 2 - logout from MAINFORM.dispose 
					XmlDocument doc = new XmlDocument();
					doc.LoadXml(readdata);
					XmlNodeList list = doc.GetElementsByTagName("command");
					// ------------------MESSAGE------------------------
					//	<command><message><from>nickname</from><to>Public</to><body>text</body></message></command>
					if(list[0].ChildNodes[0].Name == "message")
					{	
						if(list[0].ChildNodes[0].ChildNodes[1].InnerText == "Public")
						{
							chatserver.Broadcast(readdata);
						}
						else //private message
						{
							string to = list[0].ChildNodes[0].ChildNodes[1].InnerText;
							if(chatserver.FindUserRoom(to) == 0) // user is not logged in probably he/she logged out
							{
								string m = "<command><message><from>System</from><to>"+to+"</to><body>Error-> "+to+" has exited!</body></message></command>";
							chatserver.Write(client.GetStream(),m);// from
							}
							else
							{
								chatserver.Write(client.GetStream(),readdata);// from
								chatserver.Write(((TcpClient)(chatserver.ClientConnections)[to]).GetStream(),readdata);// to
							}
						}
					}
					// --------------DRAW----------------------
					//		<command><draw><point><x>x</x><y>y</y></point><type>type</type></draw></command>
					if((list[0].ChildNodes[0].Name == "draw") ||(list[0].ChildNodes[0].Name == "btn"))
					{
						chatserver.Broadcast(readdata);
					}

					// --------------LOGOUT----------------------
					//		<command><logout><username>ismail</username></logout></command>
					if(list[0].ChildNodes[0].Name == "logout")
					{
						Console.WriteLine("server->logout: "+nickname);
						chatserver.RemoveRoomUser(chatserver.RoomUsers[chatserver.FindUserRoom(nickname)-1],nickname);
						try
						{
							chatserver.RemoveConnection(nickname,client);						
						}
						catch
						{}
					chatserver.Broadcast(readdata);
					}
					

					
				//	Console.WriteLine("socketHelper->readLoop: " + readdata);



				}//WHILE

					
		}

	}
}
