package app

import (
	"chain33-pai/pkg/util"
	"chain33-pai/service/pai_service"
	"net"
	"time"
)

var (
	serial      string
	runningAddr *net.IPNet
)

func Broadcast() {
	var pai pai_service.Pai
	send := "hello world"
	if serial != "" {
		send = serial
	} else {
		ok := pai.GetConfig()
		if ok {
			send = pai.Serial
			serial = pai.Serial
		} else {
			panic("no serial no")
		}
	}
	ips, err := GetRightIPs()
	if err != nil {
		panic(err)
	}
	if len(ips) == 0 {
		panic("no ip found")
	}
	ip := ips[0]

	// 这里设置发送者的IP地址，自己查看一下自己的IP自行设定
	laddr := net.UDPAddr{
		IP:   ip.IP,
		Port: 8804,
	}

	// 这里设置接收者的IP地址为广播地址
	raddr := net.UDPAddr{
		IP:   net.IPv4(255, 255, 255, 255),
		Port: 8804,
	}
	conn, err := net.DialUDP("udp", &laddr, &raddr)
	if err != nil {
		tlog.Error("broadcast", "net error ", err)
		panic(err)
	}
	for {
		//ip 会变化
		ips, err = GetRightIPs()
		if err != nil {
			panic(err)
		}
		if len(ips) == 0 {
			panic("no ip found")
		}
		ip = ips[0]

		if runningAddr != nil && runningAddr.IP.String() != ip.IP.String() {
			laddr = net.UDPAddr{
				IP:   ip.IP,
				Port: 8804,
			}
			// 这里设置接收者的IP地址为广播地址
			raddr = net.UDPAddr{
				IP:   net.IPv4(255, 255, 255, 255),
				Port: 8804,
			}
			conn.Close()
			conn, err = net.DialUDP("udp", &laddr, &raddr)
			if err != nil {
				tlog.Error("broadcast", "net error ", err)
				panic(err)
			}
			tlog.Info("broadcast", "oldip", runningAddr.IP.String(), "newip", ip.IP.String())
		}

		runningAddr = ip
		_, err = conn.Write([]byte(send))
		if err != nil {
			tlog.Error("broadcast ", "err", err)
			time.Sleep(time.Second * 1)
			continue
		}
		tlog.Info("broadcast", "ip:", ip.IP.String(), "udp", send)
		time.Sleep(time.Second * 1)
	}

}

func GetRightIP() (ipv4 *net.IPNet, err error) {
	//ip 会变化
	ip, err := util.GetLocalIPByName("wlan0")
	if err != nil || ip == nil {
		//tlog.Error("broadcast","wlan0", err)
		ip, err = util.GetLocalIPByName("eth0")
		if err != nil {
			//tlog.Error("broadcast","eth0", err)
			ip, err = util.GetLocalIPByName("wlp3s0")
			if err != nil || ip == nil {
				//tlog.Error("broadcast","wlp3s0", err)
				ip, err = util.GetLocalIPByName("enp2s0")
				if err != nil {
					//tlog.Error("broadcast", "enp2s0",err)
					panic(err)
				}
			}
		}
	}
	return ip, err
}

func GetRightIPs() (ipv4s []*net.IPNet, err error) {
	ips := make([]*net.IPNet, 0)
	interfaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}
	for _, i := range interfaces {
		ip, err := util.GetLocalIPByName(i.Name)
		if err != nil {
			return nil, err
		}
		if ip != nil {
			ips = append(ips, ip)
			//tlog.Info("GetRightIPs","ip",ip.IP.String())
		}
	}
	//tlog.Info("GetRightIPs","ips",ips)
	return ips, nil
}
