package com.eactive.eai.adapter.socket2.protocol.cert.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.cert.codec.CertDecoder.CodecState;
import com.eactive.eai.adapter.socket2.protocol.cert.message.CertMessage;
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 CertEncoder implements ProtocolEncoder {	
	protected final Logger logger;
	protected final Logger errLogger;

	SocketAdapterContext context;
	ISocketAdapter adapter;
	
	public CertEncoder(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 {
		/*
		if (context.getTraceLevel() >= context.TRACE_LEVEL_TRACE) {
			logger.debug(context.getAdapterName() + " | <RECV> decode : " + message);
		}
		*/
		
		CodecState codecState = (CodecState) session.getAttribute(CertConstants.CODEC_KEY);

		if (codecState == null) {
			codecState = new CodecState();
			codecState.buffer.limit(CertMessage.LL_LENGTH);
			session.setAttribute(CertConstants.CODEC_KEY, codecState);
		}
		
		CertMessage m = null;
		if (message == null) {
			throw new Exception("cannot write null message.");
		} else if (message instanceof CertMessage) {
			m = (CertMessage) message;
		} else if (message instanceof ByteMessage) {
			m = new CertMessage(((ByteMessage) message).getBytes());
		} else if (message instanceof String) {
			m = new CertMessage((String) message);
		} else if (message instanceof byte[]) {
			m = new CertMessage((byte[]) message);
		} else {
			throw new Exception("cannot write unknow format message.");
		}
		
		ByteBuffer buffer = ByteBuffer.allocate(CertMessage.COMMON_HEADER_LENGTH + CertMessage.INDIVIDUAL_HEADER_LENGTH + m.getBytes().length);
		//buf.setAutoExpand(true); // Enable auto-expand for easier encoding

		// write header
//		String ll = CommonLib.getFormatString(m.getBytes().length, CertMessage.LL_LENGTH);
//		buffer.put(ll.getBytes());  							// tatal message length
		// tatal message length - left padding '0'
		//buffer.put(StringUtils.leftPad(String.valueOf(m.getValue().length + Constants.HEADER_LENGTH + Constants.TAIL_LENGTH), 7, '0').getBytes());	

		// 암호화 타입 (0:plain 1:DES 2:Plll Connect)
		//buffer.put(codecState.securityType);						
		// 판매점 아이디 (16 Byte 고정으로 앞 또는 뒤를 공백문자로 채운다)
		//buffer.put(StringUtils.leftPad("1111", 16, ' ').getBytes());	
		
		// write header
		buffer.put(m.getHeader());
		
        //write payload	
        buffer.put(m.getBytes());
        
        int mark = buffer.position();
        buffer.position(0);
		if ( context.getTraceLevel() >= context.TRACE_LEVEL_TRACE ) {
			logger.debug(context.getAdapterName() + " | CertEncoder | encode : " + CommonLib.hexDump(buffer, context));
			adapter.addRecentSendTrace(session, "CertEncoder | encode : " + CommonLib.hexDump(buffer, context));
		}
        buffer.position(mark);        
        buffer.flip();
        out.write(buffer);
	}
	
	public void dispose(IoSession session) throws Exception {
		// empty
	}
}
