package com.reyun.saas.mob.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by nolan on 16/9/22.
 * description: IP相关服务类,支持ip地址的获取、地理位置转换.
 */
public class IPAddrUtil {
    private static final Logger logger = LoggerFactory.getLogger(IPAddrUtil.class);


    static {
            String path = "/data/application/mobdna/17monipdb.dat";
            IP.load(path);
    }

    /**
     * 根据ip地址转换成对应地理位置
     *
     * @param httpServletRequest 请求实体
     * @return
     */
    public static String getLocationFromIpAddr(HttpServletRequest httpServletRequest) {
        return getLocationFromIpAddr(getIpAddr(httpServletRequest));
    }

    /**
     * 根据ip地址转换成对应地理位置
     *
     * @param ipAddr ip地址
     * @return
     */
    public static String getLocationFromIpAddr(String ipAddr) {
        if (ipAddr == null || ipAddr.isEmpty()) {
            return "unknown-unknown-unknown";
        }

        try {
            String[] tmp = IP.find(ipAddr);
            return String.format("%s-%s-%s", tmp[0], tmp[1], tmp[2]);
        } catch (Exception e) {
            logger.error("ipAddr:{}", ipAddr);
            logger.error("解析ip错误", e);
            return "unknown-unknown-unknown";
        }
    }

    /**
     * 获取IP地址
     *
     * @param request 请求实体
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if( ip.indexOf(",")!=-1 ){
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static void main(String[] args){
        String addr = getLocationFromIpAddr("1.119.176.34");
        System.out.println(addr);
    }
}
