package main

import (
	"flag"
	"fmt"
	"log"
	"net"
	"time"

	"github.com/usnistgov/ndn-dpdk/ndn"
	"github.com/usnistgov/ndn-dpdk/ndn/l3"
	"github.com/usnistgov/ndn-dpdk/ndn/sockettransport"
	"inet.af/netaddr"
)

func main() {
	target := flag.String("target", "::1", "target IP address")
	pairs := flag.Int("pairs", 1, "number of loop pairs")
	delay := flag.Duration("delay", 100*time.Millisecond, "loop delay")
	flag.Parse()
	ip, e := netaddr.ParseIP(*target)
	if e != nil {
		log.Fatalln("netaddr.ParseIP", e)
	}

	var faces []l3.Face
	for i := 0; i < *pairs*2; i++ {
		tr, e := sockettransport.Dial("udp", "", net.JoinHostPort(ip.String(), "6363"))
		if e != nil {
			log.Fatalln("sockettransport.Dial", i, e)
		}
		face, e := l3.NewFace(tr)
		if e != nil {
			log.Fatalln("l3.NewFace", i, e)
		}
		faces = append(faces, face)
	}

	for i, face := range faces {
		go func(i int, src l3.Face) {
			for pkt := range src.Rx() {
				if pkt.Interest == nil {
					continue
				}
				log.Println(">", i, pkt.Interest.Name)

				j := i + 1
				if i%2 == 1 {
					j = i - 1
				}
				dst := faces[j]
				go func(dst l3.Face, pkt *ndn.Packet) {
					time.Sleep(*delay)
					dst.Tx() <- pkt
				}(dst, pkt)
			}
		}(i, face)

		go func(i int, dst l3.Face) {
			interest := ndn.Interest{
				Name: ndn.ParseName(fmt.Sprint("/localhost/loop-initial/", i)),
			}
			dst.Tx() <- interest
		}(i, face)
	}

	select {}
}
