package peer

import (
	"log"
	"net"
	"time"
)

func RunMCReader(g Globals) {
	for {
		runMCReaderInner(g)
		time.Sleep(broadcastErrorTimeoutInterval)
	}
}

func runMCReaderInner(g Globals) {
	var (
		buf  = make([]byte, bufferSize)
		logf = func(s string, args ...any) {
			log.Printf("[MCReader] "+s, args...)
		}
	)

	conn, err := net.ListenMulticastUDP("udp", nil, multicastAddr)
	if err != nil {
		logf("Failed to bind to multicast address: %v", err)
		return
	}

	for {
		conn.SetReadDeadline(time.Now().Add(32 * time.Second))
		n, remoteAddr, err := conn.ReadFromUDPAddrPort(buf[:bufferSize])
		if err != nil {
			logf("Failed to read from UDP port): %v", err)
			return
		}

		buf = buf[:n]
		h, ok := headerFromLocalDiscoveryPacket(buf)
		if !ok {
			logf("Failed to open discovery packet?")
			continue
		}

		g.RemotePeers[h.SourceIP].Load().HandleLocalDiscoveryPacket(h, remoteAddr, buf)
	}
}
