/** (C) 1999 World Xiangqi League, Confidential, All Rights Reserved */

import java.io.*;
import java.util.*;

class Connection extends Thread {
  private Vector commands = new Vector(10);
  private boolean shutdown = false;
  private DataInputStream input;
  private PrintStream     output;

  // Called by Club.login
  Connection(DataInputStream input, PrintStream output,
	     ThreadGroup threadGroup) {
    super(threadGroup, "Connection");
    this.input  = input;
    this.output = output;
  }

  // ----------------------------------------------------------------
  // Commands producer. Club:run() is consumer.
  public void run() {    // Invoked via Club.login() call to start()
    shutdown = false;
    String line = null;
    while (!shutdown) {
      try { line = input.readLine(); } // blocks
      catch (IOException e) { line = null; }
      if (!shutdown)
	put(line);
      if (line==null) {
	Club.debug("Internet connection has failed.");
	shutdown = true;
      }
    }
  }

  public void shutdown() {
    shutdown = true;
  }

  // FIFO communications stack.
  // Newest at beginning of stack.
  private synchronized void put(String line) {
    if (line==null) line = "disconnected from server";
    commands.insertElementAt(line,0);
    //Club.verbose("put "+commands.size()+" "+line);
  }
  // Extract oldest from end of stack.
  public synchronized String get() {
    if (commands.isEmpty())
      return null;
    String line = (String)commands.lastElement();
    Club.verbose("get "+commands.size()+" "+line);    
    commands.removeElementAt(commands.size()-1);
    return line;
  }
  
  /** Send COMMAND, return appropriate true/false on success. */
  public synchronized void send(String command) {
    // Club, ChatPanel, GameCanvas, GamePanel
    Club.verbose("out "+command);
    if (shutdown) {
      Club.verbose("Connection.send abort, shutdown");
      return;
    }
    try {
      output.println(command);	// blocks
      output.flush();		// blocks
    } catch (Exception e) {
      Club.warning(e,"send "+command);
    }
  }
}
