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")
		}
	}
	ip,err := GetRightIp()
	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 = GetRightIp()
		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)
			}
			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
		}
		ips = append(ips,ip)
	}
	return ips, nil
}