package ca.sebastiendionne.grizzly.client.handler;

import java.nio.channels.SelectionKey;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.grizzly.CallbackHandler;
import com.sun.grizzly.Context;
import com.sun.grizzly.IOEvent;
import com.sun.grizzly.SelectorHandler;
import com.sun.grizzly.TCPConnectorHandler;

//Callback to receive the messages from the server
public class ProtocolChainCallbackHandler implements CallbackHandler<Context> {
	private static final Logger s_logger = LoggerFactory.getLogger(ProtocolChainCallbackHandler.class);
	
	private TCPConnectorHandler connectorHandler;
	
	public ProtocolChainCallbackHandler(TCPConnectorHandler handler){
		connectorHandler = handler;
	}
	
	public void onConnect(IOEvent<Context> e) {
		SelectionKey k = e.attachment().getSelectionKey();
		if(s_logger.isDebugEnabled()){
			s_logger.debug("Callbackhandler: OnConnect...");
		}
		try {
			connectorHandler.finishConnect(k);
		} catch (Exception ex) {
			s_logger.error("exception in CallbackHandler:" + ex.getMessage());
		}
		e.attachment().getSelectorHandler().register(k, SelectionKey.OP_READ);
	}
	
	// read event
	public void onRead(IOEvent<Context> ioEvent) {
		SelectionKey key = ioEvent.attachment().getSelectionKey();
		SelectorHandler selectorHandler = ioEvent.attachment().getSelectorHandler(); 
		
		// CALL THE PROTOCOL CHAIN
		try {
			if(key.isValid() && key.isReadable()){
				Context ctx = ioEvent.attachment();
				
				ctx.getProtocolChain().execute(ioEvent.attachment());
				
			}
		} catch (Exception ex){
			if(s_logger.isDebugEnabled()){
				s_logger.debug("IOException", ex);
			}
		    selectorHandler.getSelectionKeyHandler().cancel(key);
		}  

	}

	// write event
	public void onWrite(IOEvent<Context> e) {
		if(s_logger.isDebugEnabled()){
			s_logger.debug("onWrite");
		}
	}

}
