package com.asciibunny.bcs.test.socket;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class SocketTesterGui extends JFrame {

	private static final long serialVersionUID = 1L;
	
	private SocketTester client;
	
	private JScrollPane scrollPaneChat;
	private JTextField input;

	public JTextArea chat;

	public SocketTesterGui(String name, SocketTester client) {
		super(name);
		this.client = client;

		setDefaultCloseOperation(EXIT_ON_CLOSE);

		initContentPane();

		pack();
		setLocationRelativeTo(null);
		setVisible(true);
	}

	private void initContentPane() {
		getContentPane().setLayout(
				new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));

		chat = new JTextArea();
		{
			chat.setEditable(false);
			scrollPaneChat = new JScrollPane(chat);
			scrollPaneChat.setPreferredSize(new Dimension(200, 200));
		}

		input = new JTextField(32);
		{
			input.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					if (e.getSource().equals(input))
						if (!e.getActionCommand().equals(""))
							input();
				}
			});
			input.setMaximumSize(new Dimension(20000000, 20));
		}
		
		getContentPane().add(scrollPaneChat);
		getContentPane().add(input);
	}

	private void input() {
		String in = input.getText();
		input.setText("");
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				client.send(in);
			}
		});
	}
}
