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

import com.eactive.eai.adapter.socket2.protocol.ByteMessage;
import com.eactive.eai.adapter.socket2.protocol.ISocketAdapter;
import org.apache.mina.common.IoSession;


public class SeedServerFilter extends SeedFilter {
	public SeedServerFilter(ISocketAdapter adapter) {
		super(adapter);
	}	
	
//	@Override
//	public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception {
//		process(nextFilter, session, new ByteMessage("123"));
//	}
	
	
	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
		process(nextFilter, session, message);
	}
	
	
	private void process(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_HANDSHAKE:
//			/**
//			 * create user key & round key
//			 */
//	        filterState.userKey = m.getBytes();
//			//EgeedCodec.SeedEncRoundKey(filterState.roundKey, filterState.userKey);
//	        session.write(m.getBytes());
//	        
//			/**
//			 * change state
//			 */
//			filterState.state = State.STATE_MESSAGE;
//			setSessionState(session, filterState.state.toString());		
//			
//			nextFilter.sessionOpened(session);
//			break;

		case STATE_MESSAGE:
//			if (context.getTraceLevel() >= context.TRACE_LEVEL_TRACE) {
//				logger.debug(context.getAdapterName() + " | SeedServerFilter | messageReceived() " + m.hexDump());
//			}
			
	        byte[] decrypted = SeedCodec.decrypt(m.getBytes());       
	        m.setBytes(decrypted);
	        
//			if (context.getTraceLevel() >= context.TRACE_LEVEL_TRACE) {
//				logger.debug(context.getAdapterName() + " | SeedServerFilter | messageReceived() - after decrypt - " + m.hexDump());
//			}

			/**
			 * next filter
			 */
			nextFilter.messageReceived(session, m);
			break;
			
		default:
			throw new Exception("<RECV> invalid message during handshake .. : " + m);
		}
	}
}
