package models

import (
	"context"
	"database/sql"

	"git.paulbsd.com/paulbsd/ipbl/src/config"
	"xorm.io/xorm"
)

func GetIPsWithoutHostInfo(ctx *context.Context, config *config.Config) (apiips []string, err error) {
	res, err := config.Db.Query(`
		SELECT ip
		FROM ip
		WHERE ip NOT IN (
			SELECT ip FROM host_info)
		ORDER BY RANDOM()
		LIMIT 10;`)
	for _, r := range res {
		apiips = append(apiips, string(r["ip"]))
	}
	return
}

func ProcessHostInfo(cfg *config.Config, hostinfos []HostInfo) (err error) {
	session := cfg.Db.NewSession()
	defer session.Close()
	for _, hi := range hostinfos {
		var i IP = HostInfoToIP(session, &hi)
		i.GetOrCreate(session)
	}
	session.Commit()
	return
}

func HostInfoToIP(session *xorm.Session, hi *HostInfo) (ip IP) {
	ip = IP{
		IP: hi.IP,
		Rdns: sql.NullString{
			String: hi.Rdns,
			Valid:  true},
		City:             &City{CityName: hi.City},
		Country:          &Country{CountryName: hi.Country},
		AutonomousSystem: &AutonomousSystem{ID: 0},
	}
	return
}

type HostInfo struct {
	IP      string `json:"ip"`
	Whois   string `json:"whois"`
	Rdns    string `json:"rdns"`
	City    string `json:"city"`
	Country string `json:"country"`
}
