import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

import java.io.*;
import java.net.*;

/**
 * 
 * A simple application to send messages to "Hugo" (http://old.dsek.se/sektionen/km/hugo).<br>
 * Copyright (C) 2008 Joakim Andersson<br><br>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.<br><br>
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.<br><br>
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see &lt;http://www.gnu.org/licenses/&gt;.
 * 
 */
public class JHugo extends JFrame {
	private static final long serialVersionUID = 1L;

	public static void main(String[] args) {
		new JHugo();
	}
	
	private JTextField message;
	private JButton button;
	private JHugo self;
	
	private JHugo() {
		super("JHugo");
		
		self = this;
		
		message = new JTextField();
		button = new JButton("Send");
		
		SendListener sendListener = new SendListener();
		message.addActionListener(sendListener);
		button.addActionListener(sendListener);
		
		add(message, BorderLayout.CENTER);
		add(button, BorderLayout.EAST);
		
		// Window close listener
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) 
			{
				System.exit(0);
			}
		});
		
		pack();
		
		setMinimumSize(new Dimension(480,48));
		setLocationRelativeTo(null);
		setVisible(true);
	}
	
	private class SendListener implements ActionListener {
		public void actionPerformed(ActionEvent arg0) {
			if (message.getText().length() > 0) {
				try {
					Socket out = new Socket("hugo.dsek.lth.se", 1101); 
					out.getOutputStream().write((message.getText() + "\n").getBytes("ISO-8859-15"));
					out.close();
					message.setText("");
					JOptionPane.showMessageDialog(self, "Message was sent successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);
				} catch (IOException e) {
					JOptionPane.showMessageDialog(self, "Error connecting to Hugo!\n\n" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
				}
			} else {
				JOptionPane.showMessageDialog(self, "You must type a message first!", "Error", JOptionPane.ERROR_MESSAGE);
			}
		}
	}
}
