// TalkApplication.java
//
// This program is created by modifying an example from the book 
// _Java in a Nutshell_ by David Flanagan. You may study, use, modify, 
// and distribute this example for any purpose. This program is 
// provided WITHOUT WARRANTY either expressed or implied.
//
// (C) Henrik Björkman 1997
//
// This program will connect to a port on a server and open
// a window with one field for input from keyboard and one
// field for output received from the server.
//
// History:
// 0.0 Created by Henrik Björkman 1997-05-03


import java.io.*;
import java.net.*;
import java.awt.*;

public class TalkApplication extends Frame
{
  public static final int DEFAULT_PORT = 6789;

  int port = DEFAULT_PORT;
  String hostname;
  TalkClient client;
  int event_count=0;

  static int exit_count=1; // Do system exit if this reaches zero.

  // Just for debugging.
  static void debug(String s)
  {
    //System.out.println("TalkApplication: "+s);   
  }


  public TalkApplication(String hostname, int port)
  {
    client=new TalkClient(this,hostname,port);
    this.pack();
    this.show();
  }

  public static void usage() 
  {
    System.out.println("Usage: java Client <hostname> [<port>]");
    System.exit(0);
  }    

  public static void main(String[] args) 
  {
    int port = DEFAULT_PORT;
        
    // Parse the port specification
    if (args.length == 0) usage();
    if (args.length >= 2)  
    {
      try { port = Integer.parseInt(args[1]); }
      catch (NumberFormatException e) { usage(); }
    }
        
    new TalkApplication(args[0],port);
  }


  // This will handle all events.
  public boolean handleEvent(Event e) 
  {
    debug("handleEvent "+(event_count++));

    switch(e.id)
    {
      case Event.ACTION_EVENT:
      {
        return(client.handleEvent(e));
      }
      case Event.WINDOW_DESTROY:
      {
        debug("WINDOW_DESTROY");
        this.hide();
        this.dispose();
        if (--exit_count==0) System.exit(0);
        return true;
      }
      default:
      {
        debug("Other event");
        break;
      }
    }
    return false;
  }

}


