package com.eactive.eai.adapter.socket2.filter.validation;

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.util.regex.Matcher;
import java.util.regex.Pattern;


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

    protected SocketAdapterContext context;
	protected ISocketAdapter adapter;
	
	public ValidationFilter(ISocketAdapter adapter) {
		this.adapter = adapter;
		this.context = adapter.getContext();

	    logger    = SocketLoggerManager.getInstance().getLogger(context.getAdapterGroupName());
	    errLogger = SocketLoggerManager.getInstance().getErrLogger();
	}		
	
	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
		/*
		if (context.getTraceLevel() >= context.TRACE_LEVEL_DEBUG) {
			logger.debug(context.getAdapterName() + " | ValidationFilter | messageReceived()");
		}
		*/

		ByteMessage m = (ByteMessage) message;

		/**
		 * validation.rule
		 */
		if (!"".equals(context.getValidationRule())) {
			Matcher matcher = Pattern.compile("\\[([ ]*[0-9]+)[ ]*,([ ]*[0-9]+)[ ]*\\][ ]*=[ ]*(.+)").matcher(context.getValidationRule().trim());
			if (matcher.find()) {
			    int offset = Integer.parseInt(matcher.group(1).trim());
			    int length = Integer.parseInt(matcher.group(2).trim());
			    String re = matcher.group(3).trim();
			    
			    if (!new String(m.getBytes(offset, length)).matches(re)) {
			    	throw new Exception(context.getAdapterName() + " | data is invalid - validation.rule : " + context.getValidationRule() + "    " + m.hexDump());
			    }
			} else {
				throw new Exception(context.getAdapterName() + " | validation.rule format is invalid : " + context.getValidationRule());
			}
		}

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