package com.eactive.eai.adapter.socket2.protocol.proxy;

import com.eactive.eai.adapter.socket2.common.CommonLib;
import com.eactive.eai.adapter.socket2.protocol.ISocketAdapter;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;


public class ServerToProxyHandler extends AbstractProxyHandler {
	public ServerToProxyHandler(ISocketAdapter adapter) {
		super(adapter);
	}
	
	@Override
    public void sessionClosed(IoSession session) throws Exception {
    	super.sessionClosed(session);
    	
        if (session.getAttachment() != null) {
            ((IoSession) session.getAttachment()).setAttachment(null);
            ((IoSession) session.getAttachment()).close();
            session.setAttachment(null);
        }
        
        session.close();
    }	
    
	@Override
    public void messageReceived(IoSession session, Object message) throws Exception {
		logger.debug(session + CommonLib.hexDump((ByteBuffer) message, context));
		
		ByteBuffer rb = (ByteBuffer) message;
        ByteBuffer wb = ByteBuffer.allocate(rb.remaining());
        rb.mark();
        wb.put(rb);
        wb.flip();
        
        ((IoSession) session.getAttachment()).write(wb);
        
        rb.reset();
    }
}
