package data

import (
	"github.com/rs/zerolog/log"
	"sync"
	"thuanle.me/ip-info/configs"
)
import reader "github.com/oschwald/maxminddb-golang"

type IpDb struct {
	r  *reader.Reader
	mu sync.RWMutex
}

var (
	ins  *IpDb
	once sync.Once
)

func Ins() *IpDb {
	once.Do(func() {
		ins = &IpDb{}
		_ = ins.Reload()
	})
	return ins
}

func (d *IpDb) Reload() error {
	d.mu.Lock()
	defer d.mu.Unlock()

	if d.r != nil {
		_ = d.r.Close()
	}
	r, err := reader.Open(configs.MmdbDbFile)
	if err != nil {
		log.Err(err).Msg("Failed to open mmdb")
		return err
	}

	d.r = r
	return nil
}

func (d *IpDb) IsLoaded() bool {
	return d.r != nil
}
