package com.xunwang.ucenter.utils;

import org.apache.commons.io.IOUtils;
import org.lionsoul.ip2region.*;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;

/**
 * 位置工具类
 */
public class LocationUtils {

    private static byte[] daData = null;

    static {
        try {
            ClassPathResource resource = new ClassPathResource("ip2region.db");
            InputStream inputStream = resource.getInputStream();
            daData = IOUtils.toByteArray(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据ip获取位置
     * @param ip
     * @return
     * @throws DbMakerConfigException
     * @throws IOException
     */
    public static String getRegionFromIp(String ip) throws DbMakerConfigException, IOException {
        DbSearcher dbSearcher = new DbSearcher(new DbConfig(), daData);
        String region = null;
        if (Util.isIpAddress(ip)) {
            DataBlock dataBlock = dbSearcher.memorySearch(ip);
            region = dataBlock.getRegion(); // 中国|0|四川省|成都市|联通
            String[] split = region.split("\\|");
            String city = split[3].replaceAll("市", "");

            return city;
        }
        return null;
    }
}
