import java.awt.*;
import java.net.*;
import java.io.*;
import java.applet.*;
import mkgray.gui.ImageCanvas;

public class AskAWebm extends Applet implements Runnable {
  ChatEnvironment chat;
  Socket chatSock;
  //  BufferedReader chatFrom; // Java 1.1
  DataInputStream chatFrom; // Java 1.0
  OutputStream chatTo;
  Thread sockthread;
  String alias, mituser;
  String athenaUser;
  String curURL;

  public void init() { 
    athenaUser = getParameter("user");
  }

  public void switchEnv() {
    removeAll();
    add("Center", chat = new ChatEnvironment(this));
    chat.repaint();
    layout();
    chat.layout();
    send("locate "+athenaUser);
    send("login "+alias+" "+athenaUser);
  }

  public void start() {
    setLayout(new BorderLayout());
    System.out.println("Trying to open sockets...");
    try {
      System.out.println(getParameter("server"));
    } catch (Exception e) { System.out.println("parameter failure "+e);}
    try {
      InetAddress.getByName(getParameter("server"));
    } catch (Exception e) { System.out.println("Name service failure, dammit "+e);}
    try {
      chatSock = new Socket(InetAddress.getByName(getParameter("server")), 9005);
    } catch (Exception e) { System.out.println("Failed to create socket to server: "+e); }
    try {
      //      chatFrom = new BufferedReader(new InputStreamReader(chatSock.getInputStream())); // Java 1.1
      chatFrom = new DataInputStream(chatSock.getInputStream()); // Java 1.0
      chatTo = chatSock.getOutputStream();
    } catch (Exception e) { System.out.println("Failure!: "+e);
    Thread.currentThread().stop(); }

    add("Center", chat = new ChatEnvironment(this));
    System.out.println("Starting run thread");
    (sockthread = new Thread(this)).start();
  }

  public void stop() {
    sockthread.stop();
    removeAll();
    try {
      chatSock.close(); }
    catch (Exception e) { }
  }

  public void go() {
    if(curURL != null){
      AppletContext ac = getAppletContext();
      try {
	ac.showDocument(new URL(curURL));
      } catch (Exception e) { }
    }
  }

  public void send(String s){
    byte dst[];
    try {
      //      chatTo.write(s.getBytes()); // Java 1.1
      dst = new byte[s.length()+1];
      (new String(s+"\n")).getBytes(0, s.length()+1, dst, 0);
      chatTo.write(dst);
    } catch (Exception e) {
      chat.say("Server failing to respond.  Message not sent: "+s);
    }
  }

  public void run() {
    String fromServer;
    System.out.println("Running");
    while(true){
      try {
	fromServer = chatFrom.readLine();
	if(fromServer == null){
	  chat.say("The remote connection has been closed.");
	  return;
	}
	chat.say(fromServer);
      } catch (Exception e) { }
    }
  }

}

class LoginEnvironment extends Panel {
  Label login = new Label("Your email address or alias:");
  TextField loginName;
  Button doIt;
  Panel pan, pan2;
  AskAWebm gate;
  Image banner;

  public LoginEnvironment(AskAWebm applet){
    gate = applet;
    loginName = new TextField();
    doIt = new Button("Start Conversation with "+gate.athenaUser);
    pan = new Panel();
    pan2 = new Panel();
    setLayout(new BorderLayout());
    pan.setLayout(new GridLayout(2, 2));
    pan2.setLayout(new BorderLayout());
    pan.add(login);
    pan.add(loginName);
    try {
      pan2.add("Center", new ImageCanvas(gate.getImage(new URL("http://u6.mit.edu/~mkgray/stuff/project/java/zephyrgate/webzephyr.jpg"))));
    } catch (Exception e) { }
    pan2.add("South", pan);
    add("Center", pan2);
    add("South", doIt);
  }

  public boolean action(Event ev, Object it){
    if(ev.target == doIt){
      gate.alias = loginName.getText();
      gate.alias = gate.alias.replace(' ', '_');
      gate.switchEnv();
    }
    return true;
  }
}

class ChatEnvironment extends Panel {
  TextArea incomingMsgs;
  TextField sendThis;
  Button go;
  AskAWebm gate;

  public ChatEnvironment(AskAWebm applet){
    super();
    gate = applet;
    incomingMsgs = new TextArea(10, 60);
    incomingMsgs.setBackground(Color.gray);
    incomingMsgs.setEditable(false);
    sendThis = new TextField(60);
    go = new Button("Go to URL");
    setLayout(new FlowLayout());
    add(incomingMsgs);
    add(sendThis);
    add(go);
  }

  public boolean action(Event ev, Object it){
    if(ev.target == sendThis){
      incomingMsgs.appendText("> "+sendThis.getText());
      incomingMsgs.appendText("\n");
      gate.send(sendThis.getText());
      sendThis.setText("");
    }
    else if(ev.target == go){
      gate.go();
    }
    return true;
  }

  public void say(String s){
    if(s.substring(0,4).equals("http")){
      gate.curURL = s;
    }
    incomingMsgs.appendText(s+"\n");
  }

}

