
package org.tio.sitexxx.service.ip2region;

import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class Ip2RegionInit {

	private static final Logger log = LoggerFactory.getLogger(Ip2RegionInit.class);
	private static DbSearcher dbSearcher;

	public static void init() {
		// 使用 ClassLoader 从 JAR 包中加载资源
		try (FileInputStream fis = new FileInputStream(getDbFile())) {
			if (fis == null) {
				log.error("IP2Region database file not found in the JAR.");
				return;
			}

			// 直接通过 DbSearcher 初始化，传入文件路径字符串
			dbSearcher = new DbSearcher(new DbConfig(), getDbFile().getAbsolutePath());

			// 防止并发问题，先各查一遍
			String ip = "192.168.1.166";
			dbSearcher.memorySearch(ip);
			dbSearcher.binarySearch(ip);
			dbSearcher.btreeSearch(ip);

			log.info("IP2Region initialized and tested successfully.");
		} catch (IOException e) {
			log.error("Error reading the IP2Region database file.", e);
		} catch (Exception e) {
			log.error("Unexpected error during IP2Region initialization.", e);
		}
	}

	// 获取数据库文件路径（从临时文件读取）
	private static File getDbFile() throws IOException {
		// 将 JAR 包中的资源文件写入临时文件
		InputStream is = Ip2RegionInit.class.getClassLoader().getResourceAsStream("config/ip2region/ip2region.db");
		if (is == null) {
			throw new IOException("Resource 'config/ip2region/ip2region.db' not found in JAR file.");
		}

		File tempFile = File.createTempFile("ip2region", ".db");
		tempFile.deleteOnExit();

		try (FileOutputStream fos = new FileOutputStream(tempFile)) {
			byte[] buffer = new byte[1024];
			int length;
			while ((length = is.read(buffer)) > 0) {
				fos.write(buffer, 0, length);
			}
		}

		return tempFile;
	}
}
