using System.Net.Sockets;
using System.Net;
using System;
using System.Threading;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using System.ComponentModel;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using System.Xml;
using vclass.util;
using vclass.chat;
using vclass.whiteboard;

namespace vclass.chat.client
{
	public delegate void ClientAction(); 

	public class ChatClient:ChatStream
	{
		//external
		[DllImport("user32", EntryPoint="FlashWindow", SetLastError=true,
		 CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
		private static extern bool FlashWindow(int hwnd,bool bInvert);
				
		//delegate
//		private ClientAction action;
		private string username;
		private string password;
		private userList userlist = null;
		private chatPanel chatpanel = null;
		private WhiteBoard whiteboard = null;
		 

		//nickname
		private string nickname="";
		//the socket client	
		private TcpClient tcpc=null;
		//netwoek stream for client
		private NetworkStream stream=null;
		//listener thread
		private Thread tl=null;

		private string host =null;
		//default to port 1300
		private int port=1300;

		//data from server
		private string responseData;

		//pause_listening
		public bool pause_listening=false;
		//form_activated
		public bool form_activated=false;
		
	

	
//*****Constructor*****
		//1 parameter constructor
		public ChatClient(string _host):this(_host,1300)
		{
		}

		//2 parameter constructor
		public ChatClient(string _host,int _port)
		{
			//store the host string
			host =_host;

			//store the port number
			port=_port;
	
			//Get the connection
			try
			{	
				tcpc=Connect(host,port);
				stream=tcpc.GetStream();
				Stream=stream;
			}
			catch(Exception e)
			{
				Console.WriteLine(e);
				Environment.Exit(0);	
			}
	
	
			
			//Start Listening
			tl=new Thread(new ThreadStart(Listen));
			tl.Start();
	
			//Run the Application
	//		Application.Run(form);   
			 
		}

		
		//connect to the server
		public TcpClient Connect(string address,int port)
		{
			return new TcpClient(address,port);
		}

		public void login(string username,string password)
		{
			this.username = username;
			this.password = password;
		}

		public string getUsername()
		{
			return username;
		}
		
		public void setUserlist(userList userlist)
		{
			this.userlist = userlist;
		}

		public void setChatpanel(chatPanel chatpanel)
		{
			this.chatpanel = chatpanel;
		}

		public int setWhiteboard(WhiteBoard whiteboard)
		{
			this.whiteboard = whiteboard;
			return 1;
		}
		//read and response to mesaages
		public void Listen()
		{

			try
			{
				//this is for sending the login information to the server side
				Write(tcpc.GetStream(),"<login><username>"+username+"</username><password>"+password+"</password></login>");

				while (true)
				{
				//	action=null;

					responseData=Read();
					Console.WriteLine("ChatClient->readData: "+responseData);
					XmlDocument doc = new XmlDocument();
					doc.LoadXml(responseData);
					XmlNodeList list = doc.GetElementsByTagName("command");
				//	<command><newuser><username>ismail1</username></newuser></command>
					if(list[0].ChildNodes[0].Name == "newuser")
					{
						userlist.add(list[0].ChildNodes[0].ChildNodes[0].InnerText);
					}
				//	<command><allUsers><username>İSMAİL2</username><username>İSMAİL1</username></allUsers></command>
					if(list[0].ChildNodes[0].Name == "allUsers")
					{
						for(int i=0 ; i<list[0].ChildNodes[0].ChildNodes.Count ; i++)
						userlist.add(list[0].ChildNodes[0].ChildNodes[i].InnerText);
					}
				//  <command><draw><point><x>50</x><y>150</y></point><type>2</type><mouse>down</mouse></draw></command>
					if(list[0].ChildNodes[0].Name == "draw")
					{
						string x = list[0].ChildNodes[0].ChildNodes[0].ChildNodes[0].InnerText;
						string y = list[0].ChildNodes[0].ChildNodes[0].ChildNodes[1].InnerText;
						string type = list[0].ChildNodes[0].ChildNodes[1].InnerText;
						string mouse = list[0].ChildNodes[0].ChildNodes[2].InnerText;
						if(mouse.Equals("down"))
						{
							this.whiteboard.enterMouseDown(Int32.Parse(x),Int32.Parse(y),Int32.Parse(type));
						}
						else if(mouse.Equals("move"))
						{
							this.whiteboard.enterMouseMove(Int32.Parse(x),Int32.Parse(y),Int32.Parse(type));
						}
					}

					//"<command><btn><text>"+ this.textBox1.Text+" </text></btn></command>";

					if(list[0].ChildNodes[0].Name == "btn")
					{
						if(list[0].ChildNodes[0].ChildNodes[0].Name == "text")
						{
							string txt=list[0].ChildNodes[0].ChildNodes[0].InnerText;
							Console.WriteLine("Writing String : " + txt);
							this.whiteboard.pushButton(txt);
						}
							//string message = "<command><btn><color>"+clr.ToArgb()+"</color></btn></command>";
						else if(list[0].ChildNodes[0].ChildNodes[0].Name == "color")
						{
							string color=list[0].ChildNodes[0].ChildNodes[0].InnerText;
							Color clr=Color.FromArgb(Int32.Parse(color));
							this.whiteboard.changeColor(clr);
						}
						else if(list[0].ChildNodes[0].ChildNodes[0].Name == "font")
						{
							string font=list[0].ChildNodes[0].ChildNodes[0].InnerText;
							Font fnt=Font.FromHfont(new IntPtr(Int32.Parse(font)));
							this.whiteboard.changeFont(fnt);
						}
							//"<command><btn><undo></undo></btn></command>"
						else if(list[0].ChildNodes[0].ChildNodes[0].Name == "undo")
						{
							this.whiteboard.undo();
						}
						else if(list[0].ChildNodes[0].ChildNodes[0].Name == "redo")
						{
							this.whiteboard.redo();
						}
						else if(list[0].ChildNodes[0].ChildNodes[0].Name == "image")
						{
							Console.WriteLine("Gelen image adı : "+ list[0].ChildNodes[0].ChildNodes[0].InnerText);
							this.whiteboard.loadImage(list[0].ChildNodes[0].ChildNodes[0].InnerText);
						}
					}

				//	<command><message><from>nickname</from><to>Public</to><body>text</body><color>black</color></message></command>
					if(list[0].ChildNodes[0].Name == "message")
					{
						
						string message = list[0].ChildNodes[0].ChildNodes[0].InnerText+" : "+list[0].ChildNodes[0].ChildNodes[2].InnerText+"\n";
						string from = list[0].ChildNodes[0].ChildNodes[0].InnerText;
						string to = list[0].ChildNodes[0].ChildNodes[1].InnerText;
						string color = list[0].ChildNodes[0].ChildNodes[3].InnerText;
						string font = list[0].ChildNodes[0].ChildNodes[4].InnerText;

						if(username == to)
						{
							Console.WriteLine("username: "+username+" from: "+from);
							chatpanel.append(from,message,color,font);
						}
						else
						{
							Console.WriteLine("username: "+username+" to: "+to);
							chatpanel.append(to,message,color,font);
						}
			//		Console.WriteLine("chatClient->Loop: "+list[0].ChildNodes[0].ChildNodes[1].InnerText);
					}

			//		<command><logout><username>ismail</username></logout></command>
					if(list[0].ChildNodes[0].Name == "logout")
					{
						string user = list[0].ChildNodes[0].ChildNodes[0].InnerText;
						userlist.remove(user);
						//logout message from the server 
						chatpanel.append("Public",user +" has Exited!",Color.Red.ToArgb().ToString(),"1");
					}
									
					//if asked to pause	
					//while paused data may have been used by another method						
					while(pause_listening)Thread.Sleep(0);	
								
					//check if data had been cleared																	
					if (responseData=="") 
					{
					  continue;
				    }

			
				}  
			}
			catch
			{
		
			}     
		}//LISTEN

		
	}
}
