package jj.tech.paolu.utils;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import org.lionsoul.ip2region.xdb.Searcher;

import jakarta.servlet.http.HttpServletRequest;

public class IPUtil {
	
	public static final List<String> IP_HEADERS = Arrays.asList(
			"X-Forwarded-For", "Proxy-Client-IP", 
			"WL-Proxy-Client-IP", "HTTP_CLIENT_IP", 
			"HTTP_X_FORWARDED_FOR");
	
	public static String dbPath = "src/main/resources/ip/ip2region.xdb";
	public static Searcher searcher;
	
	static {
		try {
			byte[] vIndex = Searcher.loadContentFromFile(dbPath);
			searcher = Searcher.newWithBuffer(vIndex);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getClientIpAddr(HttpServletRequest request) {
	    return IP_HEADERS.stream()
	        .map(request::getHeader)
	        .filter(Objects::nonNull)
	        .filter(ip -> !ip.isEmpty() && !ip.equalsIgnoreCase("unknown"))
	        .findFirst()
	        .orElseGet(request::getRemoteAddr);
	}
	
	public static String getCityInfo(String ip) {
		try {
			return searcher.search(ip);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "";
	}
	
	
	
	
	
	
//	public static void main(String[] args) throws Exception {
//		System.err.println(getCityInfo("119.45.61.64"));
//		System.err.println(getCityInfo("173.249.203.214"));
//		System.err.println(getCityInfo("223.104.64.40"));
//		System.err.println(getCityInfo("220.205.252.233"));
//    }


	
	

}
