package ca.sebastiendionne.grizzly.client.handler;

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

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;
import com.sun.grizzly.util.ByteBufferFactory;

//Callback to receive the messages from the server
public class ClientCallbackHandler implements CallbackHandler<Context> {
	private static final Logger s_logger = LoggerFactory.getLogger(ClientCallbackHandler.class);
	
	private TCPConnectorHandler connectorHandler;
	private ByteBuffer response = ByteBufferFactory.allocateView(1000, false);
	
	
	public ClientCallbackHandler(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(); 
		SocketChannel socketChannel = (SocketChannel)key.channel();
		
		try {
			if(key.isValid() && key.isReadable()){
				
				// parse the responses here
			    int count = socketChannel.read(response);
			    if(count>0){
				    response.flip();
				    
				    byte[] b = new byte[(int)count];
					response.get(b);
					
					// ...... do your own logic.  You can use EchoQueryProtocolParser as example 
					
					response.clear();
					if(s_logger.isDebugEnabled()){
						s_logger.debug(new String(b)); // for debug purpose 
					}
			    }
				
			    selectorHandler.register(key, SelectionKey.OP_READ);
			}
		} catch (IOException 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");
		}
	}

}
