package ip

import (
	"dhcp/code"
	"dhcp/result"
	"errors"
	"fmt"
	"net"
)

// DetectPublicIPv4 获取公网IP
func DetectPublicIPv4(extra string) string {
	ip, err := autoDetectPublicIPv4()
	if err != nil {
		return ""
	}

	return fmt.Sprintf("%v%v", ip.String(), extra)
}

// autoDetectPublicIPv4 自动检测公网IP
func autoDetectPublicIPv4() (net.IP, error) {
	ifaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}
	for i := 0; i < len(ifaces); i++ {
		if (ifaces[i].Flags & net.FlagUp) == 0 {
			continue
		}
		addrs, _ := ifaces[i].Addrs()
		for _, address := range addrs {
			ipnet, ok := address.(*net.IPNet)
			if ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
				return ipnet.IP, nil
			}
		}
	}
	return nil, errors.New("unable to auto-detect public IPv4")
}

// GetLocalIPAndInterface 获取本地IP和网络接口
func GetLocalIPAndInterface() result.Result {
	type IPAddInterface struct {
		IP        string `json:"ip"`
		Interface string `json:"interface"`
	}

	var ipAddInterfaces []IPAddInterface

	// 获取所有网络接口
	ifaces, err := net.Interfaces()
	if err != nil {
		return result.Result{
			Status: false,
			Code:   code.SystemException,
			Msg:    "获取网络接口失败",
		}
	}
	for i := 0; i < len(ifaces); i++ {
		if (ifaces[i].Flags & net.FlagUp) == 0 {
			continue
		}
		addrs, _ := ifaces[i].Addrs()
		for _, address := range addrs {
			ipnet, ok := address.(*net.IPNet)
			if ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
				ipface := IPAddInterface{
					IP:        ipnet.IP.String(),
					Interface: ifaces[i].Name,
				}
				ipAddInterfaces = append(ipAddInterfaces, ipface)
			}
		}
	}

	return result.Result{
		Status: true,
		Code:   code.SUCCESS,
		Msg:    "获取网络接口成功",
		Data:   ipAddInterfaces,
	}
}
