
package com.games.gateway.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;

public class IpAddressUtils {
    private static final Logger log = LoggerFactory.getLogger(IpAddressUtils.class);

    public IpAddressUtils() {
    }

    public static String getIpAddress(ServerHttpRequest request) {
        String cfIp = request.getHeaders().getFirst("Cf-Connecting-IP");
        if (StringUtils.isNotEmpty(cfIp)) {
            return cfIp;
        } else {
            String awsIp = request.getHeaders().getFirst("x-original-forwarded-for");
            if (StringUtils.isNotEmpty(awsIp)) {
                return awsIp;
            } else {
                String Xip = request.getHeaders().getFirst("X-Real-IP");
                String ip = request.getHeaders().getFirst("X-Forwarded-For");
                if (StringUtils.isNotBlank(ip) && !"unKnown".equalsIgnoreCase(ip)) {
                    int index = ip.indexOf(",");
                    return index != -1 ? ip.substring(0, index) : ip;
                } else {
                    ip = Xip;
                    if (StringUtils.isNotBlank(Xip) && !"unKnown".equalsIgnoreCase(Xip)) {
                        return Xip;
                    } else {
                        if (StringUtils.isBlank(Xip) || "unknown".equalsIgnoreCase(Xip)) {
                            ip = request.getHeaders().getFirst("Proxy-Client-IP");
                        }

                        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                            ip = request.getHeaders().getFirst("WL-Proxy-Client-IP");
                        }

                        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                            ip = request.getHeaders().getFirst("HTTP_CLIENT_IP");
                        }

                        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                            ip = request.getHeaders().getFirst("HTTP_X_FORWARDED_FOR");
                        }

                        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                            ip = request.getRemoteAddress().toString();
                        }

                        return ip;
                    }
                }
            }
        }
    }
}
