package com.eactive.eai.adapter.socket2.protocol.inisafepayload.codec;

import com.eactive.eai.adapter.socket2.common.CommonLib;
import com.eactive.eai.adapter.socket2.config.SocketAdapterContext;
import com.eactive.eai.adapter.socket2.config.SocketLoggerManager;
import com.eactive.eai.adapter.socket2.protocol.ByteMessage;
import com.eactive.eai.adapter.socket2.protocol.ISocketAdapter;
import com.eactive.eai.adapter.socket2.protocol.ProtocolHandler;
import com.eactive.eai.common.util.Logger;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderAdapter;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class InisafePayloadDecoder extends ProtocolDecoderAdapter  {
	protected final Logger logger;
	protected final Logger errLogger;
	
	public static final int MAX_PAYLOAD_SIZE = 100 * 1024;   // 100KB

	private static final String DECODER_STATE_KEY = InisafePayloadDecoder.class.getName() + ".STATE";

	private static class CodecState {
		ByteBuffer 	buffer = ByteBuffer.allocate(0).setAutoExpand(true);
	}
	
	SocketAdapterContext context;
	ISocketAdapter adapter;

	public InisafePayloadDecoder(ISocketAdapter adapter) {
		this.adapter = adapter;
		this.context = adapter.getContext();

	    logger    = SocketLoggerManager.getInstance().getLogger(context.getAdapterGroupName());
	    errLogger = SocketLoggerManager.getInstance().getErrLogger();
	}

	@SuppressWarnings("static-access")
	public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception {
		if ( context.getTraceLevel() >= context.TRACE_LEVEL_TRACE ) {
			logger.debug(context.getAdapterName() + " | InisafePayloadDecoder | decode : " + CommonLib.hexDump(in, context));
			adapter.addRecentRecvTrace(session, "InisafePayloadDecoder | decode : " + CommonLib.hexDump(in, context));
		}
		
		CodecState codecState = (CodecState) session.getAttribute(DECODER_STATE_KEY);

		if ( (codecState == null) && (context.getRecvPayloadLength() > 0) ) {
			codecState = new CodecState();
			codecState.buffer.limit(context.getRecvPayloadLength());
			session.setAttribute(DECODER_STATE_KEY, codecState);
		}

		while(in.hasRemaining()) {
			session.setIdleTime(IdleStatus.BOTH_IDLE, context.getTimeout());
			if (readPayload(session, codecState, in)) {
				byte[] bytes = new byte[codecState.buffer.limit()];
				codecState.buffer.position(0);
				codecState.buffer.get(bytes);
				ByteMessage message = new ByteMessage(bytes);
				out.write(message);

    			codecState.buffer.position(0).limit(context.getRecvPayloadLength());

				if (context.isClient() && context.isPermanent() && context.isPollingUse()) {
					session.setIdleTime(IdleStatus.BOTH_IDLE, context.getPollingTimeout());
				} else {
					session.setIdleTime(IdleStatus.BOTH_IDLE, context.getIdleTimeout());
				}
			}
			session.setAttribute(ProtocolHandler.CODEC_STATE_BUFFER, CommonLib.hexDumpRead(codecState.buffer, context));
		}		
	}

	private boolean readPayload(IoSession session, CodecState codecState, ByteBuffer in) throws Exception {
        /**
         * 읽으려는 size 만큼 아직 data가 오지 못함 
         */
		if (codecState.buffer.remaining() > in.remaining()) {
        	codecState.buffer.put(in);
            return false;
        }
		
        /**
         * 읽으려는 size 에 도달
         */		
    	while(codecState.buffer.hasRemaining()) {
    		codecState.buffer.put(in.get());
    	}
		
		return true;
	}
}
