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

import com.eactive.eai.adapter.socket2.config.SocketAdapterContext;
import com.eactive.eai.adapter.socket2.protocol.ISocketAdapter;
import com.eactive.eai.adapter.socket2.protocol.cert.message.CertMessage;
import org.apache.mina.common.IoFuture;
import org.apache.mina.common.IoSession;


public class CertServerFilter extends CertFilter {
	public CertServerFilter(ISocketAdapter adapter) {
		super(adapter);
	}	
	
	
	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
		FilterState filterState = (FilterState) session.getAttribute(FILTER_STATE_KEY);

		CertMessage m = (CertMessage) message;

		switch (filterState.state) {
		case STATE_CHALLENGE:
			if (context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_TRACE) {
				logger.debug(context.getAdapterName() + " | CertServerFilter | <RECV> challenge : " + m.hexDump());
			}
			if (context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_TRACE) {
				logger.debug(context.getAdapterName() + " | CertServerFilter | <SEND> challenge : " + m.hexDump());
			}
			IoFuture future = session.write(m.getBytes());
			//future.join(context.getTimeout() * 1000L);
			
			filterState.state = State.STATE_AUTH;
			setSessionState(session, filterState.state.toString());
			break;
			
		case STATE_AUTH:
			if (context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_TRACE) {
				logger.debug(context.getAdapterName() + " | CertServerFilter | <RECV> auth : " + m.hexDump());
			}
			if (context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_TRACE) {
				logger.debug(context.getAdapterName() + " | CertServerFilter | <SEND> auth : " + m.hexDump());
			}
			future = session.write(m.getBytes()); //filterState.key);
			//future.join(context.getTimeout() * 1000L);
			
			filterState.state = State.STATE_MESSAGE;
			setSessionState(session, filterState.state.toString());
			
			nextFilter.sessionCreated(session);
			nextFilter.sessionOpened(session);
			break;
			
		case STATE_MESSAGE:
			if (context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_DEBUG) {
				logger.debug(context.getAdapterName() + " | CertServerFilter | <RECV> : " + m.hexDump());
			}
			
			nextFilter.messageReceived(session, message);
			break;
		}
	}
}
