package com.qmth.boot.api.utils;

import com.qmth.boot.api.constant.ApiConstant;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class RequestUtil implements ApiConstant {

    private static final String FIELD_IP = "_IP_";

    public static String getIpAddress(HttpServletRequest request) {
        String ip = getAttribute(request, FIELD_IP);
        if (StringUtils.isEmpty(ip)) {
            ip = request.getHeader("X-FORWARDED-FOR");
            if (StringUtils.isEmpty(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("X-Real-IP");
            }
            if (StringUtils.isEmpty(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTPCLIENTIP");
            }
            if (StringUtils.isEmpty(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            if (StringUtils.isEmpty(ip)) {
                ip = IP_UNKNOWN;
            } else if (ip.contains(",")) {
                ip = ip.split(",")[0];
            }
            request.setAttribute(FIELD_IP, ip);
        }
        return ip;
    }

    public static <T> T getAttribute(HttpServletRequest request, String name, T defaultValue) {
        Object obj = request.getAttribute(name);
        T value = null;
        if (obj != null) {
            try {
                value = (T) obj;
            } catch (Exception ignored) {
            }
        }
        return value != null ? value : defaultValue;
    }

    public static <T> T getAttribute(HttpServletRequest request, String name) {
        return getAttribute(request, name, null);
    }

}
