package app

import (
	"chain33-pai/service/pai_service"
	"chain33-pai/pkg/util"
	"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
		}
	}
	//ip 会变化
	ip,err := util.GetLocalIpByName("wlan0")
	if err != nil || ip == nil {
		tlog.Error("broadcast",err)
		ip,err = util.GetLocalIpByName("eth0")
		if err != nil {
			panic(err)
		}
	}
	// 这里设置发送者的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 会变化
		ip,err = util.GetLocalIpByName("wlan0")
		if err != nil || ip == nil {
			tlog.Error("broadcast",err)
			ip,err = util.GetLocalIpByName("eth0")
			if err != nil {
				panic(err)
			}
		}

		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)
			}
			runningAddr = ip
		}


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

	}

}
