package com.eactive.eai.adapter.socket2.protocol.fixedheader;

import com.eactive.eai.adapter.EAIException;
import com.eactive.eai.adapter.socket2.config.SocketAdapterContext;
import com.eactive.eai.adapter.socket2.protocol.TcpAdapterClient;
import com.eactive.eai.adapter.socket2.protocol.fixedheader.ack.AckClientFilter;
import com.eactive.eai.adapter.socket2.protocol.fixedheader.codec.ChunkCodecFactory;
import com.eactive.eai.adapter.socket2.protocol.fixedheader.codec.FixedHeaderCodecFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;


public class FixedHeaderClient extends TcpAdapterClient {
	public FixedHeaderClient(SocketAdapterContext context) throws Exception {
		super(context);		
		this.handler = new FixedHeaderHandler(this);
		
		if ("NONE".equals(context.getLlFieldType())) {
			config.getFilterChain().addFirst("codec", new ProtocolCodecFilter(new ChunkCodecFactory(this)));
		} else {
			config.getFilterChain().addFirst("codec", new ProtocolCodecFilter(new FixedHeaderCodecFactory(this)));
		}
		
		if ("Y".equals(context.getAckSupport())) {
			config.getFilterChain().addAfter("codec", "ack", new AckClientFilter(this));
		}
	}
	
	public Object sendMessage(Object message) throws EAIException {
		if (context.isClient() 
			&& "FIXED_LENGTH_HEADER".equals(context.getProtocol())
			&& context.isSync()
			&& !context.isPermanent()
			&& context.isBlocking()) {
			try {
				return FixedHeaderBlockingHandler.sendMessage(this, message);
			} catch(Exception e) {
				throw new EAIException(e);
			}
		} else {
			return super.sendMessage(message);
		}
	}		
}
