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

import com.eactive.eai.adapter.socket2.config.SocketAdapterContext;
import com.eactive.eai.adapter.socket2.config.SocketLoggerManager;
import com.eactive.eai.adapter.socket2.protocol.ISocketAdapter;
import com.eactive.eai.common.util.Logger;
import org.apache.mina.common.IoFilterAdapter;
import org.apache.mina.common.IoFilterChain;
import org.apache.mina.common.IoSession;


public abstract class CertFilter extends IoFilterAdapter {
	protected final Logger logger;
	protected final Logger errLogger;

    public static final String FILTER_STATE_KEY = CertFilter.class.getName() + ".STATE";
	public static final String SESSION_STATE = "SESSION_STATE";

	public enum State {
		STATE_CHALLENGE, 
		STATE_AUTH, 
		STATE_MESSAGE;
	}

	public static class FilterState {
		public State state = State.STATE_CHALLENGE;
		byte[] key;  // token?
	}	
	
    protected SocketAdapterContext context;
	protected ISocketAdapter adapter;

	protected CertFilter(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(CertFilter.class)) {
			throw new IllegalStateException("A filter chain cannot contain more than one CertFilter.");
		}
	}
	
	@Override
	public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception {
		FilterState filterState = (FilterState) session.getAttribute(FILTER_STATE_KEY);

		if (filterState == null) {
			filterState = new FilterState();
			session.setAttribute(FILTER_STATE_KEY, filterState);
		}
	}
	
	@Override
	public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception {
	}
	
	protected void setSessionState(IoSession session, String state) {
		session.setAttribute(SESSION_STATE, state);
	}
}
