package main

import (
	"errors"
	"log"
	"net"
	"os"
	"time"
)

func PostFind() string {
	file, err := os.ReadFile("finder.txt")
	if err != nil {
		log.Print(err)
	}
	addr, err := net.ResolveUDPAddr("udp", "239.255.255.250:1900")
	if err != nil {
		log.Print(err)
	}
	laddr, err := net.ResolveUDPAddr("udp", ":0") // "192.168.254.13:9000")
	if err != nil {
		log.Print(err)
	}
	// "192.168.254.13:9000")

	// conn, err := net.DialUDP("udp", laddr, addr)
	/*
		ListenUDP -- to SEND?  WAT?
		https://github.com/golang/go/issues/13391
		Ok, maybe you don't want to read it -- the developers are cranky when
		asked why Listen would be able to SEND.
	*/
	conn, err := net.ListenUDP("udp", laddr)
	if err != nil {
		log.Print(err)
	}
	defer conn.Close()

	conn.WriteTo(file, addr)
	// conn.Write(file)
	log.Println("Posted Request for devices")

	// future: Handle multiple devices
	conn.SetReadDeadline(time.Now().Add(time.Second * time.Duration(5)))
	buffer := make([]byte, 512)
	n, fromaddr, err := conn.ReadFrom(buffer) //  Read(buffer)
	log.Printf("%d, %#v, %#v", n, fromaddr, err)

	var output string = string(buffer[0:n])
	log.Printf("GOT: [%s]", output)
	// log.Printf("Read: %#v\n", buffer)
	return output
}

func FileExists(path string) bool {
	_, err := os.Stat(path)
	return !errors.Is(err, os.ErrNotExist)
}

/*
func main() {
	fmt.Println("Start:")
	PostFind()
	fmt.Println("Done!")
}
*/
