package main

import (
	"github.com/oschwald/geoip2-golang"
	"log"
	"net"
	"os"
	"path/filepath"
	"strconv"
)

var maxmindDb *geoip2.Reader

func init() {
	ex, err := os.Executable()
	if err != nil {
		log.Fatal(err)
	}
	exPath := filepath.Dir(ex)

	maxmindDb, err = geoip2.Open(exPath + "/GeoIP2-City.mmdb")
	if err != nil {
		maxmindDb, err = geoip2.Open("GeoIP2-City.mmdb")
		if err != nil {
			log.Fatal(err)
		}
	}
}
func maxmind(hit map[string]string, ip string) {
	hit["IpAddress"] = ""
	hit["RegionCountry"] = ""
	hit["RegionCountryIso"] = ""
	hit["RegionCity"] = ""

	if ip == "-" {
		return
	}

	record, err := maxmindDb.City(net.ParseIP(ip))
	if err != nil {
		log.Fatal(err)
	}
	hit["IpAddress"] = ip

	hit["RegionCountry"] = record.Country.Names["en"]
	hit["RegionCountryIso"] = record.Country.IsoCode
	hit["RegionCity"] = record.City.Names["en"]
	if record.Location.Latitude != 0 || record.Location.Longitude != 0 {
		hit["RegionLatitude"] = strconv.FormatFloat(record.Location.Latitude, 'f', 10, 64)
		hit["RegionLongitude"] = strconv.FormatFloat(record.Location.Longitude, 'f', 10, 64)
	}
}
