package com.eactive.eai.adapter.socket2.protocol.login.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.common.util.Logger;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class BindEncoder implements ProtocolEncoder {	
	protected final Logger logger;
	protected final Logger errLogger;

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

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

	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		ByteMessage m = null;
		if (message == null) {
			throw new Exception("cannot write null message.");
		} else if (message instanceof ByteMessage) {
			m = (ByteMessage) message;
		} else if (message instanceof String) {
			m = new ByteMessage((String) message);
		} else if (message instanceof byte[]) {
			m = new ByteMessage((byte[]) message);
		} else {
			throw new Exception("cannot write unknow format message.");
		}				
		
		/**
		 * ll.include = 'Y'  -  통째로 보낸다.
		 */
		if ("Y".equals(context.getLlInclude())) {
			ByteBuffer buffer = ByteBuffer.allocate(m.size() - context.getLlFieldLength());
			buffer.put(m.getBytes(0, context.getLlFieldOffset()));
			buffer.put(m.getBytes(context.getLlFieldOffset() + context.getLlFieldLength()));
			buffer.flip();
			m.setByteBuffer(buffer);
		}

		int length = m.size();
		ByteBuffer buffer = ByteBuffer.allocate(context.getLlFieldLength() + length).limit(context.getLlFieldLength() + length);

		/**
		 * ll.field.include = 'Y'  -  header 길이 포함하여 ll 을 계산한다.
		 */
		if ("Y".equals(context.getLlFieldInclude())) {
			length = length + context.getLlFieldLength();
		}

		/**
		 * ll.offset.exclude = 'Y'  -  offset 만큼의 크기를 빼서 length를 계산한다.
		 */
		if ("Y".equals(context.getLlOffsetExclude())) {
			length = length - context.getLlFieldOffset();
		}
		//길이 계산 로직에 추가하면 됨
		if (context.getLlFieldLengthAlpha() != 0 ){
			length = length + context.getLlFieldLengthAlpha();
		}
		
        ///////////////////////////////////////
		
        /**
         * [1] before-payload
         */
        buffer.put(m.getBytes(0, context.getLlFieldOffset()));
		
		/**
		 * [2] write header
		 */
    	if ("BIN".equals(context.getLlFieldType())) {
    		int tmpLength = length;
			byte[] header = new byte[context.getLlFieldLength()];
			for (int i = context.getLlFieldLength()-1; i>=0; i--) {
				header[i] = (byte) (tmpLength % 256);
				tmpLength = tmpLength / 256;
			}
    		buffer.put(header);
    	} else { // "CHAR"
    		String lenStr = CommonLib.getFormatString(length, context.getLlFieldLength());
    		buffer.put(lenStr.getBytes());
    	}
		
        /**
         * [3] after-payload
         */
        buffer.put(m.getBytes(context.getLlFieldOffset(), m.getBytes().length - context.getLlFieldOffset()));
        
        /**
         * write
         */
        int mark = buffer.position();
        buffer.position(0);
		if ( context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_TRACE ) {
			logger.debug(context.getAdapterName() + " | BindEncoder | encode : " + CommonLib.hexDump(buffer, context));
			adapter.addRecentSendTrace(session, "BindEncoder | encode : " + CommonLib.hexDump(buffer, context));
		}
        buffer.position(mark);
        buffer.flip();
		out.write(buffer);
		out.flush();
	}
	
	public void dispose(IoSession session) throws Exception {
		// empty
	}
}
