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

import com.eactive.eai.adapter.socket2.config.SocketAdapterContext;
import com.eactive.eai.adapter.socket2.config.SocketLoggerManager;
import com.eactive.eai.adapter.socket2.protocol.ISocketAdapter;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.util.IpUtil;

import org.apache.mina.common.IoFilterAdapter;
import org.apache.mina.common.IoSession;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


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

    protected SocketAdapterContext context;
	protected ISocketAdapter adapter;

	private final Set<String> blockIpList = new HashSet<String>();
	
	public BlockIpFilter(ISocketAdapter adapter) {
		this.adapter = adapter;
		this.context = adapter.getContext();

	    logger    = SocketLoggerManager.getInstance().getLogger(context.getAdapterGroupName());
	    errLogger = SocketLoggerManager.getInstance().getErrLogger();
	    
	    String[] blockList = context.getBlockIpList().split(",");
	    for (int i=0; i<blockList.length; i++) {
	    	blockIpList.add(blockList[i].trim());
	    }
	}	    

    public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception {
        if (isBlocked(session)) {
        	blockSession(session);
        } else {
        	nextFilter.sessionOpened(session);
        }
    }

    public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception {
        if (isBlocked(session)) {
        	//blockSession(session);
        } else {
        	nextFilter.sessionClosed(session);
        }
    }
    
    private void blockSession(IoSession session) {
		if (context.getTraceLevel() >= context.TRACE_LEVEL_INFO) {
			logger.info(context.getAdapterName() + " | BlockIpFilter | "+context.getBlockIpList()+" | deny connection - [" + session.toString() + "]");
		}
		session.close();
    }

    private boolean isBlocked(IoSession session) {
		SocketAddress remoteAddress = session.getRemoteAddress();
        
        if (remoteAddress instanceof InetSocketAddress) {
        	byte[] remoteAddr = ((InetSocketAddress) remoteAddress).getAddress().getAddress();
        	String remoteIp = "";
        	for (int i=0; i<remoteAddr.length; i++) {
        		if (i > 0) {
        			remoteIp += ".";
        		}
        		remoteIp += remoteAddr[i]&0xFF;
        	}
        	return IpUtil.isMatchIp(String.join(",", blockIpList), remoteIp);
        }

        return false;
    }
}
