package comment;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.applet.*;

public class CommentApplet extends Applet
{
	public void init()
	{	setSize(600, 420);
		content.setEditable(false);
		port = Integer.parseInt(getParameter("port"));
		int where = 0;	

		try
		{	URL home = getDocumentBase();	
			sock = new Socket(home.getHost(),port);
			
			InputStream grab =  sock.getInputStream();
			BufferedReader read = new BufferedReader(new InputStreamReader(grab));
			int bufLen = Integer.parseInt(read.readLine());
			if (bufLen>0) 
			{
				char [] buf = new char[bufLen];
				int length = read.read(buf,0,bufLen);
				String original = new String(buf); 
				content.setText(original);
				where = original.length();
			}
			out = new PrintStream( sock.getOutputStream() );
		}
		catch(IOException e)
		{	comments.setText("Sorry, IO Error: " + e);
		}
		add(comments);
		add(content);
		comments.addActionListener(new CommentListener());	
		setVisible(true);
		comments.requestFocus();
		content.setCaretPosition(where);
	}

	class CommentListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{	String comment = comments.getText();
			comments.setText("");
			comments.requestFocus();
			if (out != null)
			{	if (!done)
				{	content.append(comment +"\n");
					out.println(comment);  
					if(comment.equals("..")) done = true;
				}	
			}			
		}
	}
	
	private boolean done = false;
	private TextField comments = new TextField(60);
	private TextArea content = new TextArea(24, 60);
	private int port = 4443;
	private PrintStream out = null;
	private BufferedInputStream in = null;
	private Socket sock = null;
	
	public String getAppletInfo()
	{	return "Comment Blogger. Joseph Bergin (c) 2002";
	}
	
	public void start()
	{
	}
	
	public void stop()
	{	out.println(".."); // terminate the connection
		done = true;
	}
}