package dip

import (
	"fmt"
	"log"
	"net"

	"github.com/labstack/echo/v4"
	"github.com/likexian/whois-go"
	whoisparser "github.com/likexian/whois-parser-go"
)

// GetIPInfo returns IP address mail informations
func (ip *IP) GetIPInfo(c echo.Context) (err error) {
	if c.QueryParam("ip") != "" {
		ip.IP = c.QueryParam("ip")
	} else {
		ip.IP = c.RealIP()
	}

	err = ip.CheckIPAddress()
	if err != nil {
		return err
	}

	err = ip.GetHostname()
	if err != nil {
		log.Println(err)
	}

	/*err = ip.GetWhois()
	if err != nil {
		log.Println(err)
	}*/

	return
}

// CheckIPAddress check if ip is an IP address, return err if there's an error
func (ip *IP) CheckIPAddress() (err error) {
	addr := net.ParseIP(ip.IP)
	if addr == nil {
		return fmt.Errorf("Supplied string isn't an IP address \"%s\"", ip.IP)
	}
	return
}

// GetHostname assign ip.Hostname value
func (ip *IP) GetHostname() (err error) {
	revip, err := net.LookupAddr(ip.IP)
	if err != nil {
		return err
	}
	ip.Hostname = revip[0]
	return
}

// GetWhois not implemented yet
func (ip *IP) GetWhois() (err error) {
	resultraw, err := whois.Whois("example.com")
	result, err := whoisparser.Parse(resultraw)
	if err != nil {
		return
	}
	fmt.Println(result)
	return
}

// IP defines ip main struct
type IP struct {
	IP       string `json:"ip"`
	Hostname string `json:"hostname"`
	City     string `json:"city"`
	Country  string `json:"country"`
}
