package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"os/signal"
	"syscall"
	"time"

	"aoiprxkit"
)

func main() {
	mode := flag.String("mode", "rtp", "rtp|sap")
	group := flag.String("group", "239.69.0.1", "IPv4 multicast group")
	port := flag.Int("port", 5004, "UDP port")
	iface := flag.String("iface", "", "network interface name")
	pt := flag.Int("pt", 97, "expected RTP payload type")
	rate := flag.Int("rate", 48000, "sample rate")
	ch := flag.Int("ch", 2, "channels")
	flag.Parse()

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	switch *mode {
	case "sap":
		listener, err := aoiprxkit.NewSAPListener(aoiprxkit.SAPListenerConfig{
			Group:         aoiprxkit.DefaultSAPGroup,
			Port:          aoiprxkit.DefaultSAPPort,
			InterfaceName: *iface,
			ReadBuffer:    1 << 20,
		}, func(a aoiprxkit.SAPAnnouncement) {
			fmt.Printf("SAP session: name=%q group=%s port=%d pt=%d encoding=%s rate=%d ch=%d delete=%v\n",
				a.ParsedSDP.SessionName,
				a.ParsedSDP.MulticastGroup,
				a.ParsedSDP.Port,
				a.ParsedSDP.PayloadType,
				a.ParsedSDP.Encoding,
				a.ParsedSDP.SampleRateHz,
				a.ParsedSDP.Channels,
				a.Delete,
			)
		})
		if err != nil {
			log.Fatal(err)
		}
		if err := listener.Start(ctx); err != nil {
			log.Fatal(err)
		}
		defer listener.Stop()
		<-ctx.Done()

	default:
		cfg := aoiprxkit.DefaultConfig()
		cfg.MulticastGroup = *group
		cfg.Port = *port
		cfg.InterfaceName = *iface
		cfg.PayloadType = uint8(*pt)
		cfg.SampleRateHz = *rate
		cfg.Channels = *ch

		var packets uint64
		rx, err := aoiprxkit.NewReceiver(cfg, func(frame aoiprxkit.PCMFrame) {
			packets++
			if packets%100 == 0 {
				fmt.Printf("delivered packet seq=%d ts=%d samples=%d source=%s\n", frame.SequenceNumber, frame.Timestamp, len(frame.Samples), frame.Source)
			}
		})
		if err != nil {
			log.Fatal(err)
		}
		if err := rx.Start(ctx); err != nil {
			log.Fatal(err)
		}
		defer rx.Stop()

		ticker := time.NewTicker(2 * time.Second)
		defer ticker.Stop()

		for {
			select {
			case <-ctx.Done():
				fmt.Println("stopping")
				return
			case <-ticker.C:
				fmt.Printf("stats: %+v\n", rx.Stats())
			}
		}
	}
}
