package com.xhkjedu.utils;

import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.IOException;

/**
 * @Description 解析ip归属地
 * @Author WN
 * Date 2022/11/27 22:31
 **/
@Slf4j
public class IpRegionUtil {

    public String getIpForAddress(String ip,String dbPath){
        String region = "";
        // 1、创建 searcher 对象
        // String dbPath = ConfigKey.ipregiondb;
        Searcher searcher = null;
        try {
            searcher = Searcher.newWithFileOnly(dbPath);
        } catch (IOException e) {
//            System.out.printf("failed to create searcher with `%s`: %s\n", dbPath, e);
            log.error("创建searcher失败："+ e.getMessage());
            return null;
        }

        // 2、查询
        try {
//            long sTime = System.nanoTime();
            region = searcher.search(ip);
//            long cost = TimeUnit.NANOSECONDS.toMicros((long) (System.nanoTime() - sTime));
//            System.out.printf("{region: %s, ioCount: %d, took: %d μs}\n", region, searcher.getIOCount(), cost);
            if(N_Utils.isNotEmpty(region)){
                region = region.replace("0|","").replace("|"," ");
            }
        } catch (Exception e) {
//            System.out.printf("failed to search(%s): %s\n", ip, e);
            log.error("根据ip获取地址失败："+ e.getMessage());
            return null;
        }

        // 3、关闭资源
        try {
            searcher.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return region;
    }
}
