package fr.umlv.ir2.tcp;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class UpperCaseNonBlockingServer {
  final static int DEFAULT_PORT = 1234; 
  private final ServerSocketChannel serverChannel;
  final static int SIZE = 1024;
  
  private final Selector selector = Selector.open();
  
  public UpperCaseNonBlockingServer(int port) throws IOException {
    serverChannel = ServerSocketChannel.open();
    serverChannel.socket().bind(new InetSocketAddress(port)); 
  }
  
  public UpperCaseNonBlockingServer() 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());
  }
  
  /**
   * Reads and writes bytes on clientChannel.
   * Returns false if connection is terminated.
   */
  boolean useConnection(SocketChannel clientChannel) throws IOException {
    
    ByteBuffer bbIn = ByteBuffer.allocate(SIZE);
    ByteBuffer bbOut = ByteBuffer.allocate(SIZE);    
    int bytes = 0;
    while ((bytes = clientChannel.read(bbIn)) > 0) {
      bbIn.flip();
      serve(bbIn,bbOut);
      bbOut.flip();
      clientChannel.write(bbOut);
      bbIn.clear();
      bbOut.clear();
    }
    if (bytes==-1) {
      System.out.println("End of connection...");
      return false; // end of stream
    }
    return true; // nothing more to read by now
  }
  
  /**
   * Full non blocking version.
   */
  public void launchNonBlocking() throws IOException {
    serverChannel.configureBlocking(false);
    serverChannel.register(selector, SelectionKey.OP_ACCEPT);
    // This method could be invoked in main or in
    // any another thread
    runWithoutHandler();
  }
  
  /**
   * Handles the selection of accepted connections
   * and ready-to-read channels.
   */
  public void runWithoutHandler() {
    Set<SelectionKey> selectedKeys = selector.selectedKeys();
    while (true) {
      try {
        selector.select();
        for(Iterator<SelectionKey> iKeys = selectedKeys.iterator(); iKeys.hasNext(); ) {
          SelectionKey key = iKeys.next();
          // channel could be ServerSocketChannel...
          if (key.isAcceptable()) {
            ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
            System.out.println("server socket channel for " 
                + ssc.socket().getLocalSocketAddress() + " is ready to accept");
            if (!acceptConnection(ssc)) {
              // problem with the server socket
              key.cancel();
              ssc.close();
              return;
            }
            iKeys.remove();
            continue;
          }
          // ... or channel could be SocketChannel...   
          if (key.isReadable()) {
            SocketChannel clientChannel = (SocketChannel) key.channel();
            System.out.println("channel for " 
                + clientChannel.socket().getRemoteSocketAddress() + " is ready to read");
            if (!useConnection(clientChannel)) {
              // end of stream
              key.cancel();
              clientChannel.close();
            }
            iKeys.remove();
            continue;
          }
        }
      } catch(IOException ioe) {
        ioe.printStackTrace();
      }
    }
  }
  
  /**
   * Accept connection comming on the server socket
   * channel and register it to read data from clients.
   * Returns false if problem occurs with the server socket.
   */
  boolean acceptConnection(ServerSocketChannel ssc) throws IOException {
    SocketChannel sc = null;
    try {
      sc = ssc.accept();
    } catch(IOException ioe) {
      ioe.printStackTrace(System.err);
      return false;
    }
    sc.configureBlocking(false);
    sc.register(selector,SelectionKey.OP_READ);    
    return true;
  }
  
  
  /**
   * Main for test.
   */ 
  public static void main(String[] args) throws IOException {
    UpperCaseNonBlockingServer server;
    if(args.length == 0) {
      server =
        new UpperCaseNonBlockingServer();
    } else {
      server =
        new UpperCaseNonBlockingServer(Integer.parseInt(args[0]));
    }
    server.launchNonBlocking();
  }
}
