package chatModule;
import utility.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.net.*;
public class ChatClientHandler extends ClientHandler
{

	AgentIdentity id ;
	public Gui g = null;
	boolean loggedIn = false;
	protected EventListenerList changeListeners = new EventListenerList() ;

	public ChatClientHandler()
	{

		g =new Gui();

	}
	public ChatClientHandler(InputStream in, OutputStream out)
	{
		super(in,out);
		g =new Gui();

	}


	public void doThis(Response res)
	{

		if (loggedIn)
		{
			if( res.getResponseType().compareTo("Chatting") == 0)
			{
				ChatMessage cm = (ChatMessage)res.getObject();
				//System.out.println("Got Chatting message:");
				g.chatArea.append("\n" + cm.id.getLoginName() + ": " + cm.message);
			}
			else if( res.getResponseType().compareTo("Allert") == 0)
			{
				String got = (String)res.getObject();
				JOptionPane.showMessageDialog(null, got);
			}
			else
				System.out.println("in doThis method: Unknown response"+res.getResponseType());
		}
	}
	public void setAgentId (AgentIdentity id)
	{
		this.id = id;
	}
	public class Gui extends JInternalFrame
	{
		//int WIDTH = 405;
		//int HEIGHT = 324;
		Container frameContainer;
		JTextField chatField = new JTextField(15);
		JButton button = new JButton("Send");
		public TextArea chatArea =new TextArea();
		Label label = new Label("Chat here:");
		public Gui()
		{
			super("Chatting",false,true,false,true);
			System.out.println("Building GUI");
			buildGUI();
			//setSize(WIDTH,HEIGHT);
			//setVisible(true);
			setupEventHandlers();
			//setLF();
		}
		void buildGUI()
		{
			chatArea.setEditable(false);
			//chatArea.setLineWrap(true);
			//chatArea.setWrapStyleWord(true);
			frameContainer = getContentPane();
			frameContainer.setLayout(new BorderLayout());
			//JScrollPane chat = new JScrollPane(chatArea);
			//frameContainer.add(chat,BorderLayout.CENTER);
			frameContainer.add(chatArea,BorderLayout.CENTER);
			JPanel panelContainer  = new JPanel();
			panelContainer.setLayout(new FlowLayout());
			panelContainer.add(label);
			panelContainer.add(chatField);
			panelContainer.add(button);
			frameContainer.add(panelContainer,BorderLayout.SOUTH);
			setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
		}
		void setupEventHandlers()
		{
			addInternalFrameListener(new WindowHandler());
			button.addActionListener(new ButtonHandler());

		}
		public void showGui()
		{
			loggedIn = true;
			setVisible(true);
		}

		void setLF()
		{
			String laf = UIManager.getSystemLookAndFeelClassName();
			try
			{
				UIManager.setLookAndFeel(laf);
			}
			catch (UnsupportedLookAndFeelException exc)
			{
				System.err.println("Unsupported: " + laf);
			}
			catch (Exception exc)
			{
				System.err.println("Error loading " + laf);
			}
		}

		public void addChangeListener(ChangeListener x)
		{
			changeListeners.add (ChangeListener.class, x);

		}
		public void removeChangeListener(ChangeListener x)
		{
			changeListeners.remove (ChangeListener.class, x);
		}
		protected void fireChange()
		{

			ChangeEvent c = new ChangeEvent(this);

			Object[] listeners = changeListeners.getListenerList();

			for (int i = listeners.length-2; i >= 0; i -= 2)
			{
				if (listeners[i] == ChangeListener.class)
				{
					ChangeListener cl = (ChangeListener)listeners[i+1];
					cl.stateChanged(c);
				}
			}
		}

		public class ButtonHandler implements ActionListener
		{
			public void actionPerformed(ActionEvent e)
			{
				String msg = chatField.getText();
				if (msg.length() > 0)
				{
      					try
					{
        	        			ChatMessage cm = new ChatMessage(id,msg);
						Request req =new Request(cm,"Chatting");
						ClientHeader ch = new ClientHeader(req);
						sendRequest(ch);
            					
        	        			chatField.setText("");
      					}
      					catch (Exception ex)
					{
      					}
				}
			}
		}
		public class WindowHandler extends InternalFrameAdapter

		{

			public void internalFrameClosed(InternalFrameEvent e)
			{
				fireChange();
				RemoveConnection rmc = new RemoveConnection(id);
				Request req = new Request(rmc,"RemoveConnection");
				ClientHeader toBeSent = new ClientHeader(req);
				try
				{
					sendRequest(toBeSent);
				}
				catch(Exception ex)
				{
					ex.printStackTrace();
				}
				removeConnection();
			}
		}
	}
}

