package cn.lihongjie.coal.ip;


import jakarta.annotation.PostConstruct;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.InetAddress;

@Service
@Slf4j
@Transactional
public
class IpQueryService {

    @Autowired Environment environment;

    @Value("${geolite2.url}")
    private String geolite2DownloadUrl;

    @Value("classpath:ip/ip2region.xdb")
    Resource dbFile;
    private Searcher searcher;

    private static boolean isPrivateAddress(InetAddress inetAddress) {
        byte[] addressBytes = inetAddress.getAddress();
        int byte1 = addressBytes[0] & 0xff;
        int byte2 = addressBytes[1] & 0xff;

        return (byte1 == 10) ||
               (byte1 == 172 && (byte2 >= 16 && byte2 <= 31)) ||
               (byte1 == 192 && byte2  == 168);
    }

    @SneakyThrows
    public static void main(String[] args){
        System.out.println(isPrivateAddress(InetAddress.getByName("192.168.0.1")));
    }

    @SneakyThrows
    @PostConstruct
    public void init() {


        // 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
        try {
            searcher = Searcher.newWithBuffer(dbFile.getContentAsByteArray());
        } catch (Exception e) {
            log.warn("failed to new searcher with buffer", e);
            return;
        }
        log.info("加载 ip2region.db 成功");
    }

    @SneakyThrows
    public String query(String ipaddr) {

        if (searcher != null) {
            InetAddress ipAddress = InetAddress.getByName(ipaddr);
            if (ipAddress.isAnyLocalAddress()) {
                return "服务器本机地址";
            }
            if (ipAddress.isLoopbackAddress()) {
                return "本地回环地址";
            }
            if (isPrivateAddress(ipAddress)) {
                return "内网地址";
            }


            try {

                String search = searcher.search(ipaddr);
                return search.replace("|0|", "").replace("|", "");
            } catch (Exception e) {
                log.warn("failed to search ip2region {}", ipaddr, e);
                return "";
            }
        }

        return null;
    }
}
