package com.fdkankan.ucenter.geo;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.model.CountryResponse;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;

public class IPLocationService {
    private DatabaseReader dbReader;

    public IPLocationService(String dbPath) throws IOException {
        ClassPathResource resource = new ClassPathResource(dbPath);
        InputStream inputStream = resource.getInputStream();
        dbReader = new DatabaseReader.Builder(inputStream).build();
    }

    public String getCountryByIP(String ip) {
        try {
            InetAddress ipAddress = InetAddress.getByName(ip);
            CountryResponse response = dbReader.country(ipAddress);
            return response.getCountry().getName();
        } catch (Exception e) {
            return "Unknown";
        }
    }

    public IPLocation getLocationByIP(String ip) {
        try {
            InetAddress ipAddress = InetAddress.getByName(ip);
            CityResponse response = dbReader.city(ipAddress);

            IPLocation location = new IPLocation();
            location.setIp(ip);
            location.setCountry(response.getCountry().getName());
            location.setCountryCode(response.getCountry().getIsoCode());
            location.setCity(response.getCity().getName());
            location.setLatitude(response.getLocation().getLatitude());
            location.setLongitude(response.getLocation().getLongitude());

            return location;
        } catch (Exception e) {
            return null;
        }
    }

    public void close() throws IOException {
        if (dbReader != null) {
            dbReader.close();
        }
    }
}


