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

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


public class EchoProtocolHandler extends ProtocolHandler {
	public EchoProtocolHandler(ISocketAdapter adapter) {
		super(adapter);
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		if (!(message instanceof ByteBuffer)) {
			return;
		}

		ByteBuffer rb = (ByteBuffer) message;

		synchronized(this) {
			messageRecv++;
		}
		
		if (context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_TRACE) {
			logger.debug(context.getAdapterName() + " | <RECV> : " + CommonLib.hexDump(rb, context));
		}

		if (!context.isSync()) {
			return;
		}

		ByteBuffer wb = ByteBuffer.allocate(rb.remaining());
		wb.put(rb);
		wb.flip();
		
		if ( context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_TRACE ) {
			logger.debug(context.getAdapterName() + " | <SEND> : " + CommonLib.hexDump(wb, context));
		}

		session.write(wb).join();
		
		synchronized(this) {
			messageSend++;
		}
		
		if ( context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_DEBUG ) {
			if (message instanceof byte[]) {
				logger.debug(context.getAdapterName() + " | <SEND> " + CommonLib.hexDump((byte[]) message, true, context));
			    adapter.addRecentSend(session, CommonLib.hexDump((byte[]) message, true, context ));
			} else if (message instanceof String) {
				logger.debug(context.getAdapterName() + " | <SEND> " + CommonLib.hexDump(((String) message).getBytes(), true, context));
			    adapter.addRecentSend(session, message.toString());
			} else {
				logger.debug(context.getAdapterName() + " | <SEND> " + message);
			    adapter.addRecentSend(session, message.toString());
			}
		}
	}
}
