package peer

import (
	"log"
	"net"
	"net/netip"
)

type ConnReader struct {
	Globals
	conn *net.UDPConn
	buf  []byte
}

func NewConnReader(g Globals, conn *net.UDPConn) *ConnReader {
	return &ConnReader{
		Globals: g,
		conn:    conn,
		buf:     make([]byte, bufferSize),
	}
}

func (r *ConnReader) Run() {
	for {
		r.handleNextPacket()
	}
}

func (r *ConnReader) handleNextPacket() {
	buf := r.buf[:bufferSize]
	n, remoteAddr, err := r.conn.ReadFromUDPAddrPort(buf)
	if err != nil {
		log.Fatalf("Failed to read from UDP port: %v", err)
	}

	if n < headerSize {
		return
	}

	remoteAddr = netip.AddrPortFrom(remoteAddr.Addr().Unmap(), remoteAddr.Port())

	buf = buf[:n]
	h := parseHeader(buf)

	r.RemotePeers[h.SourceIP].Load().HandlePacket(h, remoteAddr, buf)
}
