package socket

import (
	"fmt"
	"net"
	"pbx-api-gin/internal/app/stc/active"
	"pbx-api-gin/pkg/utils"
	"time"
)

var Conn net.Conn
var Conn8 net.Conn

var ConnToSlave net.Conn

const RemotePort = 10100
const LocalPort = 10201
const LocalPort8 = 10202

const LocalServerPort = 10000

const RemoteAddr = "10.0.11.11"

const RemoteAddr8 = "10.0.11.81"

func IsIPExists(targetIP string) (bool, error) {
	// 解析目标 IP
	utils.LoggerDebug.Printf("Checking device IP , Set CabNumber ......")
	ip := net.ParseIP(targetIP)
	if ip == nil {
		return false, fmt.Errorf("invalid IP address: %s", targetIP)
	}

	interfaces, err := net.Interfaces()
	if err != nil {
		return false, err
	}

	for _, iface := range interfaces {
		addrs, err := iface.Addrs()
		if err != nil {
			continue // 忽略无法读取地址的接口
		}
		for _, addr := range addrs {
			if ipnet, ok := addr.(*net.IPNet); ok && ipnet.IP != nil {
				// 精确匹配 IP（忽略掩码，只看地址本身是否一致）
				if ipnet.IP.Equal(ip) ||
					(ip.To4() != nil && ipnet.IP.To4() != nil && ipnet.IP.To4().Equal(ip.To4())) {
					return true, nil
				}
			}
		}
	}
	return false, nil
}

// Get eth0 IP
func SetMasterCabNum() {

	count := 0

getIP:

	utils.LoggerDebug.Printf("Checking system IP  ....")
	ext1, err := IsIPExists("10.0.11.11")
	if err != nil {
		utils.LoggerDebug.Printf("Check IP 10.0.11.11 err :%+v", err)
	}
	// Init cab1 number and master role
	if ext1 {
		active.CabNum = "1"
		active.Master = true
		return
	}

	ext8, err := IsIPExists("10.0.11.81")
	if err != nil {
		utils.LoggerDebug.Printf("Check IP 10.0.11.81 err:%+v", err)
	}
	// Init cab8 number and master role
	if ext8 {
		active.CabNum = "8"
		active.Master = false
		return
	}

	if !(ext1 || ext8) {
		if count < 5 {
			count++
			time.Sleep(time.Second * 2)
			goto getIP
		}
		utils.LoggerDebug.Printf("Can not get device IP ! Set Cabnum=1  Master=true by default .")

		active.CabNum = "1"
		active.Master = true
	}

}
