package com.red.circle.gateway.util;

import com.red.circle.tool.core.net.IPvUtils;
import com.red.circle.tool.core.text.StringPool;
import com.red.circle.tool.core.text.StringUtils;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Objects;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * @author pengliang on 2024/1/12
 */
public interface IpUtils {


  /**
   * <p>
   * 192.168.1.120, 192.168.1.130, 192.168.1.100 用户真实IP为： 192.168.1.110
   * </p>
   */
  static String getIpAddr(ServerHttpRequest request) {
    return IPvUtils.getIpAddr(headKey -> getHeaderVal(request, headKey), () -> {
      InetSocketAddress socketAddress = request.getRemoteAddress();
      if (Objects.isNull(socketAddress)) {
        return StringPool.EMPTY;
      }
      InetAddress address = socketAddress.getAddress();
      return Objects.nonNull(address) ? address.getHostAddress() : socketAddress.getHostString();
    });
  }

  private static String getHeaderVal(ServerHttpRequest request, String key) {
    HttpHeaders headers = request.getHeaders();

    List<String> values = headers.get(key);

    if (values == null) {
      return StringPool.EMPTY;
    }

    return values.stream().filter(StringUtils::isNotBlank).findFirst().orElse(StringPool.EMPTY);
  }

}
