import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Frame;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;

/**
 * @author Milan Ruzicka
 *
 */

public class ChatFrame extends Frame {

	JTextArea textArea;
	JTextField textField;
	JTextField nameTextField;
	JButton button;
	JPanel panel;
	String name;
	JScrollPane textScrollPane;
	
	private MyCanvas parentWindow;

	public ChatFrame(MyCanvas parent) {
		setTitle("Chat");
		setPreferredSize(new Dimension(320,330));
		setSize(new Dimension(320,330));
		
		addWindowListener(new WindowAdapter() {
	        public void windowClosing(WindowEvent evt) {
	            Frame frame = (Frame)evt.getSource();
	    
	            frame.setVisible(false);
    
	        }
	    });
		setResizable(true);
		
		name = "anon" + Math.round(Math.random()*9999);
		
		
		panel = new JPanel();
		panel.setPreferredSize(new Dimension(100,100));		
		parentWindow = parent;
		panel.setLayout(new GridBagLayout());
		
		
		nameTextField = new JTextField(12);
		nameTextField.setText(new String(name));
		nameTextField.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				name = new String(nameTextField.getText());
			}
		});
		
		
		textArea = new JTextArea(15,35);
		textArea.setEditable(false);
		textArea.append("*****   Welcome to chatroom   ***** \n");
	    
	    
	    textScrollPane = new JScrollPane(textArea,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

		textField = new JTextField(27);
		textField.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				if (textField.getText().length() != 0) parentWindow.sendTool(new ChatMessage("<" + nameTextField.getText()+ "> " + textField.getText()));
				textField.setText("");
			}
		});
		
		
        GridBagConstraints c = new GridBagConstraints();
        
        c.weightx = 1.0;
        c.weighty = 0.0;
        panel.add(new JLabel("Nickname"), c);
        
        c.weightx = 2.0;
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.HORIZONTAL;
        panel.add(nameTextField, c);

        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.weighty = 1.0;
        panel.add(textScrollPane, c);
        
        c.weightx = 0.0;
        c.weighty = 0.0;
        
        c.fill = GridBagConstraints.HORIZONTAL;
        panel.add(textField, c);
        
    	add(panel);
	}
	
	public void messageReceived(ChatMessage t){
		textArea.append(t.text+"\n");
		this.setVisible(true);
	}

}