package com.eactive.eai.adapter.socket2.protocol.xecure3.envelope;


import com.eactive.eai.adapter.socket2.config.SocketAdapterContext;
import com.eactive.eai.adapter.socket2.config.SocketLoggerManager;
import com.eactive.eai.adapter.socket2.protocol.ByteMessage;
import com.eactive.eai.adapter.socket2.protocol.ISocketAdapter;
import com.eactive.eai.common.util.Logger;
import org.apache.mina.common.IoFilterAdapter;
import org.apache.mina.common.IoSession;

import java.io.*;


public class Xecure3EnvelopeFilter extends IoFilterAdapter {
	protected final Logger logger;
	protected final Logger errLogger;

//	private static final String NEXT_FILTER = Xecure3EnvelopeFilter.class.getName() + ".NextFilter";
	protected static final String FILTER_STATE_KEY = Xecure3EnvelopeFilter.class.getName() + ".STATE";
	protected static final String SESSION_STATE = "SESSION_STATE";

	protected enum State {
		STATE_HANDSHAKE,
		STATE_FINAL,
		STATE_MESSAGE;
	}

	protected static class FilterState {
		public State  state = State.STATE_MESSAGE;
	}
	
    protected SocketAdapterContext context;	
	protected ISocketAdapter adapter;
	
	public Xecure3EnvelopeFilter(ISocketAdapter adapter) {
		this.adapter = adapter;
		this.context = adapter.getContext();

	    logger    = SocketLoggerManager.getInstance().getLogger(context.getAdapterGroupName());
	    errLogger = SocketLoggerManager.getInstance().getErrLogger();
	}
	
	public boolean isPollingPattern(ByteMessage m) throws Exception {
		ByteMessage bm = m;
		if ("Y".equals(context.getLlInclude())) {
			bm = (new ByteMessage())
			    .append(m.getBytes(0, context.getLlFieldOffset()))
			    .append(m.getBytes(context.getLlFieldOffset() + context.getLlFieldLength()));
		}
		
		if ((context.isPollingReceiver() && bm.getString().matches(context.getPollingResponsePattern()))
				|| (context.isPollingSender() && bm.getString().matches(context.getPollingRequestPattern())))
			return true;
		
		return false;
	}
	
	protected void setSessionState(IoSession session, String state) {
		session.setAttribute(SESSION_STATE, state);
	}
	
	protected String getSessionState(IoSession session) {
		return (String) session.getAttribute(SESSION_STATE);
	}
	
    protected byte[] readFile(String filename) throws FileNotFoundException, IOException	{
		File file = new File(filename);
		int fsize = (int)file.length();
		byte[] buffer = new byte[fsize];
		
		try (
			FileInputStream fis = new FileInputStream(filename);
			BufferedInputStream bis = new BufferedInputStream(fis);
		) {
			bis.read(buffer);			
		}catch(Exception ex) {
			throw ex;
		}
		return buffer;
	}
}