package fr.upem.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

public abstract class ChannelHandler {
    /* ByteBuffer must always be in write-mode at the beginning and at the end of every
     * method call
     */
	private ByteBuffer in;
	private ByteBuffer out;
	private SocketChannel channel;
	private SelectionKey key;
	
	public ChannelHandler(SelectionKey key,int bufferSize){
	   	in = ByteBuffer.allocate(bufferSize);
	   	out = ByteBuffer.allocate(bufferSize);
	   	this.key=key;
	   	channel=(SocketChannel) key.channel();
	}
	
	public void doRead() throws IOException {
		if (channel.read(in)==-1) channel.shutdownInput();
		process();
		if (updateFlags()) {
			try {channel.close();} catch (IOException e) {};
		}
	}
	
	public void doWrite() throws IOException {
		out.flip();
		channel.write(out);
		out.compact();
		process();
		if (updateFlags()) {
			try {channel.close();} catch (IOException e) {};
		}
	}

	// Process the in buffer 
    public void process() {
    	// TODO
    }
    
    // This method updates the interestOps of the key
    // and return true if the connection with the client 
    // is done and false otherwise
    public abstract boolean updateFlags(){
    	// TODO
    }
}
