package com.eactive.eai.adapter.socket2.protocol.xc3epb.handshake;

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.IoFilterAdapter;


public abstract class Xc3EpbFilter extends IoFilterAdapter {
	protected final Logger logger;
	protected final Logger errLogger;
    
    protected static final String ENCODING = "UTF-8";

	private static final String NEXT_FILTER = Xc3EpbFilter.class.getName() + ".NextFilter";
	protected static final String FILTER_STATE_KEY = Xc3EpbFilter.class.getName() + ".STATE";
	protected static final String SESSION_STATE = "SESSION_STATE";
	protected static final String XC3_SESSION_KEY = "XC3_SESSION_KEY";
	protected static final String ENCRYPTED_YN_KEY = "ENCRYPTED_YN_KEY";
	protected static final String TERMINAL_KEY = "TERMINAL_KEY";

	protected enum State {
		STATE_KEYINIT,
		STATE_KEYFINAL,
		STATE_HANDSHAKE,
		STATE_MESSAGE;
	}

	protected static class FilterState {
		public State  state = State.STATE_MESSAGE;  //State.STATE_HANDSHAKE;
	}
	
    protected SocketAdapterContext context;
	protected ISocketAdapter adapter;
	
	public Xc3EpbFilter(ISocketAdapter adapter) {
		this.adapter = adapter;
		this.context = adapter.getContext();

	    logger    = SocketLoggerManager.getInstance().getLogger(context.getAdapterGroupName());
	    errLogger = SocketLoggerManager.getInstance().getErrLogger();
	}
	
//	@Override
//	public void onPreAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception {
//		if (parent.contains(Xc3EpbFilter.class)) {
//			throw new IllegalStateException("A filter chain cannot contain more than one Xc3EbpFilter.");
//		}
//		
//		IoSession session = parent.getSession();
//		session.setAttribute(NEXT_FILTER, nextFilter);
//	}
	
	public boolean isPollingPattern(ByteMessage m) throws Exception {
		ByteMessage bm = m;
		if ("Y".equals(context.getLlInclude())) {
			bm = (new ByteMessage())
			    .append(m.getBytes(0, context.getLlFieldOffset()))
			    .append(m.getBytes(context.getLlFieldOffset() + context.getLlFieldLength()));
		}
		
		if ((context.isPollingReceiver() && bm.getString().matches(context.getPollingResponsePattern()))
				|| (context.isPollingSender() && bm.getString().matches(context.getPollingRequestPattern())))
			return true;
		
		return false;
	}
	
//	protected void setSessionState(IoSession session, String state) {
//		session.setAttribute(SESSION_STATE, state);
//	}
//	
//	protected String getSessionState(IoSession session) {
//		return (String) session.getAttribute(SESSION_STATE);
//	}
}
