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.KeyGenerator;


public class DesServerFilter extends DesFilter {
	public DesServerFilter(ISocketAdapter adapter) {
		super(adapter);
	}	
	
	@Override
	public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception {
		/**
		 * create secret key
		 */
		FilterState filterState = (FilterState) session.getAttribute(FILTER_STATE_KEY);
        filterState.secretKey = KeyGenerator.getInstance("DES").generateKey();

        /**
         * send secret key
         */
        /*
		ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(filterState.secretKey);
		oos.close();
		WriteFuture future = session.write(new ByteMessage(bos.toByteArray()));
		//future.join(context.getTimeout() * 60L);
		*/
        byte[] keyBytes = filterState.secretKey.getEncoded();
//		WriteFuture future = session.write(new ByteMessage(keyBytes));      
		session.write(new ByteMessage(keyBytes));
		/**
		 * change state
		 */
		filterState.state = State.STATE_MESSAGE;
		setSessionState(session, filterState.state.toString());		

		/**
		 * next filter
		 */
		nextFilter.sessionOpened(session);
	}
	
	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
		ByteMessage m = (ByteMessage) message;
		if (context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_TRACE) {
			logger.debug(context.getAdapterName() + " | DesServerFilter | messageReceived() " + m.hexDump());
		}

		FilterState filterState = (FilterState) session.getAttribute(FILTER_STATE_KEY);
        DesCodec des = new DesCodec(filterState.secretKey);
        byte[] decrypted = des.decrypt(m.getBytes());
        m = new ByteMessage(decrypted);
		if (context.getTraceLevel() >= SocketAdapterContext.TRACE_LEVEL_TRACE) {
			logger.debug(context.getAdapterName() + " | DesServerFilter | messageReceived() - after decrypt - " + m.hexDump());
		}

		/**
		 * next filter
		 */
		nextFilter.messageReceived(session, m);
	}
}
