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

/**
 * The <code>JavlleServerHandler</code> handles single client connection
 * @author  Rimon Barr
 * @version 1.0
 */

class JavlleServerHandler implements Runnable, Observer {
  
  private Socket s;
  private Board b;
  private BufferedReader is;
  private PrintWriter os;

  /**
   * Initialise connections and streams to client
   */
  public JavlleServerHandler(Socket s, Board b) throws IOException {
    this.s=s;
    this.b=b;
    is=new BufferedReader(new InputStreamReader(s.getInputStream()));
    os=new PrintWriter(s.getOutputStream());
  }

  /**
   * Receive board strings and update local board object
   * Since all players are observing it, 
   * the update method will get called.
   */
  public void run() {
    b.addObserver(this);
    update(b, null);
    try {
      while(true) {
        String s=is.readLine();
        if(s==null) break;
        b.fromString(s);
      }
    }
    catch (IOException e) {
    }
    b.deleteObserver(this);
    try {
      s.close();
    }
    catch (IOException e1) {}
  }

  /**
   * Board information has changed so send it back
   */
  public void update(Observable o, Object arg) {
    os.println(b);
    os.flush();
  }


}
