package fr.umlv.tcp;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * A Server that replies, for each line of text it receives from a client, 
 * with the uppercase line of the same text. This server is iterative, 
 * that is it only could accept a single client once.
 * 
 * @author duris
 */
public class UpperCaseIterativeServer {
  final static int DEFAULT_PORT = 1234; 
  private final ServerSocketChannel serverChannel;
  private final static int SIZE = 1024;
  
  /**
   * Constructs a server bound to the given port. 
   * @param port the port to bind the server socket.
   * @throws IOException If an I/O error occurs,
   * if the bind operation fails, or if the socket is already bound.
   */
  public UpperCaseIterativeServer(int port) throws IOException {
    serverChannel = ServerSocketChannel.open();
    serverChannel.socket().bind(new InetSocketAddress(port)); 
  }

  /**
   * Constructs a server bound to the default port. 
   * @throws IOException If an I/O error occurs,
   * if the bind operation fails, or if the socket is already bound.
   */
 public UpperCaseIterativeServer() throws IOException {
    this(DEFAULT_PORT);
  }
    
  /**
   * Writes in buffer <code>out</code> the uppercase
   * version of the string found in buffer <code>in</code>.
   */
  void serve(ByteBuffer in, ByteBuffer out) throws IOException {
    // version "brutale" sans tenir compte du codage!!!
    byte[] buf = new byte[in.remaining()];
    in.get(buf);
    out.put(new String(buf).toUpperCase().getBytes());
  }

  /*
   * Full blocking iterative version.
   */
  public void launchBlockingIterative() throws IOException {
    SocketChannel clientChannel = null;
    ByteBuffer bbIn = ByteBuffer.allocate(SIZE);
    ByteBuffer bbOut = ByteBuffer.allocate(SIZE);    
    while (true) {
      // accept a new client connection 
      clientChannel = serverChannel.accept();
      try {
        System.err.println("New connection accepted from " 
            + clientChannel.socket().getRemoteSocketAddress());
        System.err.println("Channel is " 
            + (clientChannel.isOpen()?"open":"closed"));
        // while not end of stream...
        while(clientChannel.read(bbIn) != -1) {
          bbIn.flip();
          serve(bbIn,bbOut);
          bbOut.flip();
          clientChannel.write(bbOut);
          bbIn.clear();
          bbOut.clear();
        }
      } catch(IOException ioe) {
        ioe.printStackTrace(System.err);
      } finally {
        System.err.println("Ending connection with " 
            + clientChannel.socket().getRemoteSocketAddress());
        bbIn.clear();
        bbOut.clear();
        try {
          clientChannel.close();
        } catch(IOException e) {
          e.printStackTrace(System.err);
        }
        System.err.println("Channel is " 
            + (clientChannel.isOpen()?"open":"closed"));  
      }
    }
  }
    
  /**
   * Main for test.
   */ 
  public static void main(String[] args) throws IOException {
    UpperCaseIterativeServer server;
    if(args.length == 0) {
      server = new UpperCaseIterativeServer();
    } else {
      server = new UpperCaseIterativeServer(Integer.parseInt(args[0]));
    }
    server.launchBlockingIterative();
  }
}
