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

import com.eactive.eai.adapter.socket2.protocol.ISocketAdapter;
import com.eactive.eai.adapter.socket2.protocol.ProtocolHandler;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.TrafficMask;

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 abstract class AbstractProxyHandler extends ProtocolHandler {
//	private static Charset CHARSET = Charset.forName("iso8859-1");
	private final Set<String> l4SkipIpList = new HashSet<>();
	private final Set<String> blockIpList = new HashSet<>();
	
	protected AbstractProxyHandler(ISocketAdapter adapter) {
		super(adapter);
		
	    String[] l4SkipList = context.getL4SkipIpList().split(",");
	    for (int i=0; i<l4SkipList.length; i++) {
	    	l4SkipIpList.add(l4SkipList[i].trim());
	    }
	    
	    String[] blockList = context.getBlockIpList().split(",");
	    for (int i=0; i<blockList.length; i++) {
	    	blockIpList.add(blockList[i].trim());
	    }	    

	}

	@Override
    public void sessionCreated(IoSession session) throws Exception {
		if (!(isCheck(session,l4SkipIpList) || isCheck(session,blockIpList))){
			session.setTrafficMask(TrafficMask.NONE);
		}
    } 
    private boolean isCheck(IoSession session , Set<String> list) {
		SocketAddress remoteAddress = session.getRemoteAddress();
        
        if (remoteAddress instanceof InetSocketAddress) {
        	for (String allow : list) {
	            byte[] remoteAddr = ((InetSocketAddress) remoteAddress).getAddress().getAddress();
	            String remoteIp = "";
	            for (int i=0; i<remoteAddr.length; i++) {
	                if (i > 0) {
	                	remoteIp += ".";
	                }
	                remoteIp += remoteAddr[i]&0xFF;
	            }
	            
	            if (allow.indexOf('*') == -1) {          	
	            	if (allow.equals(remoteIp)) {
	            		return true;
	            	}
	            } else {
					String allowRegexp = allow.replaceAll("\\*", "[0-9]+");
					Matcher matcher = Pattern.compile(allowRegexp, Pattern.CASE_INSENSITIVE).matcher(remoteIp);
					if (matcher.matches()) {
						return true;
					}
	            }
        	}
        }

        return false;
    }

}
