package com.fdkankan.ucenter.geo;

import cn.hutool.extra.servlet.ServletUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class IPUtils {
    private static IPLocationService locationService;

    static {
        try {
            locationService = new IPLocationService("geo/GeoLite2-City.mmdb");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getCountry(String ip) {
        if (locationService != null) {
            return locationService.getCountryByIP(ip);
        }
        return "Unknown";
    }

    public static Map<String, String> getLocationInfo(String ip) {
        Map<String, String> info = new HashMap<>();
        if (locationService != null) {
            IPLocation location = locationService.getLocationByIP(ip);
            if (location != null) {
                info.put("country", location.getCountry());
                info.put("city", location.getCity());
                info.put("latitude", String.valueOf(location.getLatitude()));
                info.put("longitude", String.valueOf(location.getLongitude()));
            }
        }
        return info;
    }

    public static String getIpAddr(HttpServletRequest request) {
        return ServletUtil.getClientIP(request);
    }

}
