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

public class ChatClient extends Thread {
  protected ObjectInputStream iObjStrem;
  protected ObjectOutputStream oObjStream;

  protected ChatFrame frame ;
  protected Socket server ;
  
  public ChatClient (String title, Socket s)
        throws IOException {
    super(title) ;
    server = s ;
    frame = newFrame(title, this);
  }
  
  protected ChatFrame newFrame(String title, ChatClient cc) { 
    return new ChatFrame(title,cc) ; 
  }
  
  public void SendString( String s ) throws IOException {
    oObjStream.writeObject( s ) ; 
  }

  public void run () {
    try {
      iObjStrem = new ObjectInputStream(server.getInputStream());
      oObjStream = new ObjectOutputStream(server.getOutputStream());     
      frame.show ();

      while (true) {
        String line = (String)iObjStrem.readObject();
        frame.AddText(line);
      }
    } catch (Exception ex) {
      ex.printStackTrace ();
    } finally {
      try {
        server.close ();
        System.out.println( "Connessione col server persa." ) ;
        frame.dispose() ;
        System.exit(1);
      } catch (IOException ex) {
        ex.printStackTrace ();
      }
    }
  }

  public static void main (String args[]) throws IOException {
    if (args.length != 2)
      throw new RuntimeException ("Sintassi: ChatClient <host> <port>");

    Socket s = new Socket (args[0], Integer.parseInt (args[1]));
    (new ChatClient ("ChatClient "+args[0]+":"+args[1], s)).start();
  }
}

class ChatFrame extends Frame {
    ChatClient chatClient ;
    protected TextArea output = new TextArea();
    protected TextField input = new TextField();
    
    public ChatFrame( String title, ChatClient cc ) { 
        super(title) ;
        chatClient = cc ;
        setLayout(new BorderLayout ());
        add ("Center", output);
        output.setEditable(false);
        add ("South", input);
        pack ();        
        input.requestFocus();   
    }
    
    public boolean handleEvent (Event e) {
        if ((e.target == input) && (e.id == Event.ACTION_EVENT)) {
            try {
                chatClient.SendString((String) e.arg);
            } catch (IOException ex) {
                ex.printStackTrace();
                chatClient.stop ();
            }
            input.setText ("");
            return true;    
        } else if ((e.target == this) && (e.id == Event.WINDOW_DESTROY)) {
            chatClient.stop ();
            hide ();
            return true;
        }
        return super.handleEvent (e);
    }
    
    public void AddText( String s )
    {
        output.appendText( s + "\n" ) ;
    }        
}
    
