package com.eactive.eai.adapter.socket2.protocol.inisafe2020.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.inisafe2020.handshake.InisafeFilter;
import com.eactive.eai.adapter.socket2.protocol.inisafe2020.handshake.InisafeFilter.FilterState;
import com.eactive.eai.common.util.Logger;
import org.apache.commons.lang3.StringUtils;
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 InisafeEncoder implements ProtocolEncoder {	
	protected final Logger logger;
	protected final Logger errLogger;

	SocketAdapterContext context;
	ISocketAdapter adapter;
	
	public InisafeEncoder(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.");
		}
		
		boolean isHandshakeState = false;
		FilterState filterState = (FilterState) session.getAttribute(InisafeFilter.FILTER_STATE_KEY);
		if (filterState != null && filterState.state != InisafeFilter.State.STATE_MESSAGE) {
			isHandshakeState = true;
		}
		
		if (isHandshakeState) {
			encodeHandshake(session, m, out);
		} else {
			encodeMessage(session, m, out);
		}
	}
	
	
	private void encodeHandshake(IoSession session, ByteMessage m, ProtocolEncoderOutput out) throws Exception {
		int length = m.size();
		int totalLength = InisafeConstants.COMMON_PART_LENGTH + length;
		
		ByteBuffer buffer = ByteBuffer.allocate(totalLength).limit(totalLength);

        /**
         * [1] common ll
         */
		String commonLL = CommonLib.getFormatString(totalLength-InisafeConstants.COMMON_PART_LENGTH, InisafeConstants.COMMON_LL_LENGTH);
        buffer.put(commonLL.getBytes());                	// 1 전문송신 Byte 수 5 N * 비고 1) 참조

        /**
         * [2] common rest
         */
        buffer.put(getTransactionType(session));             	// 2 거래구분코드 9 AN * 비고 2) 참조
		buffer.put("BOK".getBytes());                   	// 3 System ID 3 A * BOK (단, 증권예탁결제원간 거래는 DVP)
		buffer.put("0000".getBytes());                  	// 4 전문종별 코드 4 N * 비고 3) 참조
		buffer.put("YYYYMMDD".getBytes());              	// 5 영업일자 8 N * YYYYMMDD
		buffer.put("    ".getBytes());                  	// 6 STATUS 4 N * 비고 4) 참조
		buffer.put("0000".getBytes());                  	// 7 응답코드 4 AN * <별첨1> 참조
		buffer.put("00000000000000000000".getBytes());  	// 8 전문관리번호 20 N * 비고 5) 참조
		buffer.put("YYYYMMDDhhmmss".getBytes());        	// 9 전문전송시간 14 N * YYYYMMDDhhmmss
		buffer.put("00000000000000000000".getBytes());  	// 10 참조번호 20 N B 비고 6) 참조
		buffer.put("1051".getBytes());                  	// 11 송신기관 4 N * <별첨3> 참조, 비고 7)참조
		buffer.put("1016".getBytes());                  	// 12 수신기관 4 N * <별첨3> 참조, 비고 8)참조
		buffer.put("N".getBytes());                     	// 13 암호화 여부 1 A * Y/N
		buffer.put("001".getBytes());                   	// 14 전송횟수 3 N * 전송한 횟수 * 최초전송번호 : 1
		buffer.put(StringUtils.leftPad("", 65).getBytes()); // 15 공란 65 A * Space
		buffer.put("                ".getBytes());      	// 16 참가기관 ID 16 AN SR 한국은행에 등록된 ID
		buffer.put("                ".getBytes());      	// 17 참가기관 비밀번호 16 AN SR 참가기관의 비밀번호
		
		/**
		 * [3] individual part
		 */
		buffer.put(m.getBytes());
        
        /**
         * write
         */
        int mark = buffer.position();
        buffer.position(0);
		if (context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_TRACE) {
			logger.debug(context.getAdapterName() + " | InisafeEncoder | encode (handshake) : " + CommonLib.hexDump(buffer, context));
			adapter.addRecentSendTrace(session, "InisafeEncoder | encode (handshake) : " + CommonLib.hexDump(buffer, context));
		}
        buffer.position(mark);
        buffer.flip();
		out.write(buffer);
	}

	
	private byte[] getTransactionType(IoSession session) throws Exception {
		FilterState filterState = (FilterState) session.getAttribute(InisafeFilter.FILTER_STATE_KEY);
		if (filterState == null) {
			throw new Exception("session does not have filter state");
		}

		switch (filterState.state) {
		case STATE_INIT :
			if (adapter.getContext().isClient()) {
				return "000000001".getBytes();
			} else {
				return "000000002".getBytes();
			}
		case STATE_UPDATE :
			if (adapter.getContext().isClient()) {
				return "000000003".getBytes();
			} else {
				return "000000004".getBytes();
			}
		case STATE_FINAL :
			return "000000005".getBytes();
		default :
			throw new Exception("invalid state");			
		}		
	}

	private void encodeMessage(IoSession session, ByteMessage m, ProtocolEncoderOutput out) throws Exception {
		/**
		 * copy byte[] to buffer
		 */
		int length = m.size();	
		ByteBuffer buffer = ByteBuffer.allocate(length).limit(length);
		buffer.put(m.getBytes());
        
        /**
         * write
         */
        int mark = buffer.position();
        buffer.position(0);
		if (context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_TRACE) {
			logger.debug(context.getAdapterName() + " | InisafeEncoder | encode : " + CommonLib.hexDump(buffer, context));
			adapter.addRecentSendTrace(session, "InisafeEncoder | encode : " + CommonLib.hexDump(buffer, context));
		}
        buffer.position(mark);
        buffer.flip();
		out.write(buffer);
	}

	
	public void dispose(IoSession session) throws Exception {
		// empty
	}
}
