package main

import (
	"bytes"
	"fmt"
	"net"
	"strconv"
	"strings"
)

func generateIP(startIP, endIP string) (string, error) {
	start := net.ParseIP(startIP)
	end := net.ParseIP(endIP)

	if start == nil || end == nil {
		return "", fmt.Errorf("invalid IP address")
	}

	ip := incrementIP(start)
	if ip.Equal(end) {
		return "", fmt.Errorf("invalid IP address")
	}

	return ip.String(), nil
}

func incrementIP(ip net.IP) net.IP {

	ip = ip.To4()
	if ip == nil {
		return ip // Return if it's not a valid IPv4 address
	}

	for i := len(ip) - 1; i >= 0; i-- {
		if ip[i] < 255 {
			ip[i]++
			return ip
		}
		ip[i] = 0 // Reset to 0 if it overflows
	}
	return ip // Return the incremented IP
}

// checkIPInRange 检查给定 IP 是否在指定的范围内
func checkIPInRange(ipStr, startStr, endStr string) (bool, error) {
	ip := net.ParseIP(ipStr)
	start := net.ParseIP(startStr)
	end := net.ParseIP(endStr)

	if ip == nil || start == nil || end == nil {
		return false, fmt.Errorf("invalid IP address")
	}

	return bytesCompare(ip, start) >= 0 && bytesCompare(ip, end) <= 0, nil
}

// bytesCompare 对 IP 进行字节比较
func bytesCompare(a, b net.IP) int {
	return bytes.Compare(a, b)
}

func ipToInt(ip net.IP) int64 {
	// 将 IP 地址转换为整数
	return int64(ip[0])<<24 + int64(ip[1])<<16 + int64(ip[2])<<8 + int64(ip[3])
}

func generateSequentialMAC(start [6]byte, count int) [][6]byte {
	macAddresses := make([][6]byte, count)

	for i := 0; i < count; i++ {
		macAddresses[i] = start
		// 递增MAC地址
		for j := 5; j >= 0; j-- {
			if start[j]++; start[j] != 0 {
				break
			}
		}
	}

	return macAddresses
}

// parseMACString 将字符串格式的 MAC 地址转换为 [6]byte 类型
func parseMACString(macStr string) ([6]byte, error) {
	macParts := strings.Split(macStr, ":")
	if len(macParts) != 6 {
		return [6]byte{}, fmt.Errorf("invalid MAC address format: %s", macStr)
	}

	var mac [6]byte
	for i, part := range macParts {
		num, err := strconv.ParseUint(part, 16, 8)
		if err != nil {
			return [6]byte{}, fmt.Errorf("invalid MAC address format: %s", macStr)
		}
		mac[i] = byte(num)
	}
	return mac, nil
}
func formatMAC(mac [6]byte) string {
	return fmt.Sprintf("%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5])
}

func main() {
	inRange, err := checkIPInRange("192.168.2.123", "192.168.2.123", "192.168.2.254")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(inRange)
}

func NowIP() string {
	return "192.168.1.13"
}

func GenerateIP(start, end string) string {
	//startIp := net.ParseIP(start)
	//endIp := net.ParseIP(end)
	//
	//ip := net.ParseIP(NowIP())
	return ""
}

// isValidMACAddressInRange 检查 MAC 地址是否在指定范围内
func isValidMACAddressInRange(mac [6]byte, networkType int) bool {
	startMAC, err := parseMACString("23:E0:00:00:00:00")
	if err != nil {
		return false
	}
	endMAC, err := parseMACString("23:E0:00:00:00:FF")
	if err != nil {
		return false
	}

	for i := 0; i < 6; i++ {
		if mac[i] < startMAC[i] || mac[i] > endMAC[i] {
			return false
		}
	}
	return true
}
