package net.yyc.common.core.util;

import org.apache.commons.io.FileUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Ip工具类
 *
 * @author jimmy
 * @version 1.0.0
 * @date 2022-12-21 14:41
 */
public final class Ip2Region {

    private static final Logger log = LoggerFactory.getLogger(Ip2Region.class);

    /**
     * 搜索器
     */
    private Searcher searcher;

    /**
     * 从 dbPath 加载整个 xdb 到内存。
     */
    public Ip2Region() {

        try {
            byte[] cBuff = Searcher.loadContentFromFile("/ip2region.xdb");
            searcher = Searcher.newWithBuffer(cBuff);
        } catch (IOException e) {
            log.warn("从dbPath加载整个xdb到内存失败", e);
        }
    }

    /**
     * 获取IP属地
     * <p>
     * 格式为：[province]·[city]
     * </p>
     *
     * @param remoteIp 远程IP
     * @return IP属地
     */
    public String toRegion(final String remoteIp) throws RuntimeException {

        try {

            // 查询IP属地
            long sTime = System.nanoTime();
            String search = searcher.search(remoteIp);
            long cost = TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - sTime);
            log.info("{region: {}, ioCount: {}, took: {} μs}", search, searcher.getIOCount(), cost);

            // 封装为固定格式[province]·[city]
            search = search.replace("|0", "").replace("0|", "");
            String[] split = search.split("\\|");
            return (split.length == 2) ? split[0] + "·" + split[1] : split[1] + "·" + split[2];

        } catch (Exception e) {
            log.error("获取IP属地失败", e);
            throw new RuntimeException(e.getMessage());
        }
    }

}
