package com.eactive.eai.adapter.socket2.protocol.des.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 org.apache.mina.common.IoSession;

import javax.crypto.spec.SecretKeySpec;


public class DesClientFilter extends DesFilter {
	public DesClientFilter(ISocketAdapter adapter) {
		super(adapter);
	}	
	
	@Override
	public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception {
		// empty
	}
	
	@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_HANDSHAKE:
	        /**
	         * read secret key
	         */
			/*
			ByteArrayInputStream bis = new ByteArrayInputStream(m.getBytes()); 
			ObjectInputStream ois = new ObjectInputStream(bis);
			filterState.secretKey = (SecretKey) ois.readObject();
			ois.close();
			*/
			filterState.secretKey = new SecretKeySpec(m.getBytes(), "DES");

			/**
			 * change state
			 */
			filterState.state = State.STATE_MESSAGE;
			setSessionState(session, filterState.state.toString());		
			nextFilter.sessionOpened(session);
			break;

		case STATE_MESSAGE:
	        DesCodec des = new DesCodec(filterState.secretKey);
	        byte[] decrypted = des.decrypt(m.getBytes());
	        m = new ByteMessage(decrypted);

			///*
			if (context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_DEBUG) {
				logger.debug(context.getAdapterName() + " | DesClientFilter | <RECV> after decrypt : " + m.hexDump());
			}
			//*/

			nextFilter.messageReceived(session, m);
			break;

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