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

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


public class CertClientFilter extends CertFilter {
	public CertClientFilter(ISocketAdapter adapter) {
		super(adapter);
	}	
	
	@Override
    public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception {
//		FilterState filterState = (FilterState) session.getAttribute(FILTER_STATE_KEY);
		
		CertMessage mm = new CertMessage();
		if (context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_TRACE) {
			logger.debug(context.getAdapterName() + " | CertClientFilter | <SEND> challenge : " + mm.hexDump());
		}
//		IoFuture future = session.write(mm.getBytes());
		session.write(mm.getBytes());
		//future.join(context.getTimeout() * 1000L);
	}
	
	
	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
		FilterState filterState = (FilterState) session.getAttribute(FILTER_STATE_KEY);

		ByteMessage m = (ByteMessage) message;

		switch (filterState.state) {
		case STATE_CHALLENGE:
			if (context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_TRACE) {
				logger.debug(context.getAdapterName() + " | CertClientFilter | <RECV> challenge : " + m.hexDump());
			}
			CertMessage mm = new CertMessage();
			if (context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_TRACE) {
				logger.debug(context.getAdapterName() + " | CertClientFilter | <SEND> auth : " + mm.hexDump());
			}
//			IoFuture future = session.write(mm.getBytes());
			session.write(mm.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() + " | CertClientFilter | <RECV> auth : " + m.hexDump());
			}
			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() + " | CertClientFilter | <RECV> : " + m.hexDump());
			}
			nextFilter.messageReceived(session, message);
			break;

			
		default:
			throw new Exception("<RECV> invalid message during handshake .. : " + m);
		}
	}	
}
