package ru.micord.ervu.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * @author Adel Kalimullin
 */
public final class NetworkUtils {
  private static final Logger LOGGER = LoggerFactory.getLogger(NetworkUtils.class);
  private static final String IP_HEADER = "X-Forwarded-For";
  private static final String UNKNOWN = "unknown";

  private NetworkUtils() {
  }

  public static String getServerIp() {
    try {
      InetAddress inetAddress = InetAddress.getLocalHost();
      return inetAddress.getHostAddress();
    }
    catch (UnknownHostException e) {
      LOGGER.error("Failed to get local IP address", e);
      return UNKNOWN;
    }
  }

  public static String getClientIp(HttpServletRequest request) {
    String ip = request.getHeader(IP_HEADER);
    if (StringUtils.hasText(ip) && !ip.equalsIgnoreCase(UNKNOWN)) {
      return ip.split(",")[0].trim();
    }
    else {
      return request.getRemoteAddr();
    }
  }

  public static String getHostName(String ip) {
    try {
      InetAddress inetAddress = InetAddress.getByName(ip);
      return inetAddress.getHostName();
    }
    catch (UnknownHostException e) {
      LOGGER.error("Unknown host for IP {}", ip, e);
      return UNKNOWN;
    }
  }
}
