package bootstrap

import (
	"fmt"
	"github.com/lionsoul2014/ip2region/binding/golang/xdb"
	"strings"
)

var cBuffData []byte

func InitIpFile() {
	// 1、从 dbPath 加载整个 xdb 到内存
	dbPath := "./ip2region.xdb"
	cBuff, err := xdb.LoadContentFromFile(dbPath)
	if err != nil {
		fmt.Printf("failed to load content from `%s`: %s\n", dbPath, err)
		return
	}
	cBuffData = cBuff
}

/* 通过id地址获取省份 并发使用时候 每个goruiting 需要创建一个独立的search */
func FindAddressByIp(ip string) (string, string) {
	// 2、用全局的 cBuff 创建完全基于内存的查询对象。
	searcher, err := xdb.NewWithBuffer(cBuffData)
	if err != nil {
		fmt.Printf("failed to create searcher with content: %s\n", err)
		return "", ""
	}

	// do the search
	// var tStart = time.Now()
	region, err := searcher.SearchByStr(ip)
	if err != nil {
		fmt.Printf("failed to SearchIP(%s): %s\n", ip, err)
		return "", ""
	}
	data := strings.Split(region, "|")
	// fmt.Printf("{region: %s, took: %s}\n", data, time.Since(tStart))
	return data[2], data[3]
}
