package fr.upem.tcp;


import java.io.Closeable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.Channel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.UnsupportedCharsetException;



public class TemplateServer {

	final private int maxThreads;
	final private ServerSocketChannel ss;

	public TemplateServer(int listeningPort, int maxThreads) throws IOException {
		this.maxThreads=maxThreads;
		ss = ServerSocketChannel.open();
		ss.bind(new InetSocketAddress(listeningPort));	
	}


	private static void usage() {
		System.out.println("Usage : listeningPort nbThreads");
	}

	public static void main(String[] args) throws NumberFormatException, IOException {
		if (args.length!=2) {
			usage();
			return;
		}
		final TemplateServer server = new TemplateServer(Integer.parseInt(args[0]),  Integer.parseInt(args[1]));
		server.launch();
	}

	public void launch() {
		System.out.println("Starting TCPLsServer");
		for (int i = 0; i < maxThreads; i++) {
			new Thread( new Runnable() {

				SocketChannel s;
				
				private void process() throws IOException{
					  // TODO
					}


					private void silentlyClose(Closeable s) {
						try {
							if (s!=null) s.close();
						} catch (IOException e) {
							// Ignore
						}
					}
					
				public void run() {
					while(!Thread.currentThread().isInterrupted()) {
						try{
							synchronized (ss) {
								s = ss.accept();
							}

						} catch (IOException e) {
							silentlyClose(ss);
							return;
						}

						try{
							process();
						} catch (Exception e) {
							// Ignore all exceptions 
						} finally {
							silentlyClose(s);
						}
					} 
				}
			}).start();
		}
	}


	
}

