package main

import (
	"flag"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"strings"

	"golang.org/x/net/http2"
	"google.golang.org/grpc"
	"google.golang.org/grpc/examples/route_guide/routeguide"
)

const (
	itemCount = 100
	itemSize  = 1 << 10
)

func main() {
	addr := flag.String("addr", "127.0.0.1:8080", "Listen address")
	useGRPC := flag.Bool("grpc", true, "Use gRPC http/2 implementation")
	flag.Parse()

	http2.VerboseLogs = true

	lis, err := net.Listen("tcp", *addr)
	if err != nil {
		log.Fatalf("Listen err=%q", err)
	}

	s := grpc.NewServer()
	routeguide.RegisterRouteGuideServer(s, new(guide))

	if *useGRPC {
		err = s.Serve(lis)
		if err != nil {
			log.Fatalf("Serve err=%q", err)
		}
	} else {
		hs := &http2.Server{}
		for {
			c, err := lis.Accept()
			if err != nil {
				log.Fatalf("Accept err=%q", err)
			}
			go hs.ServeConn(c, &http2.ServeConnOpts{
				Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
					s.ServeHTTP(w, r)
					if true {
						return
					}

					log.Printf("method=%q url=%q", r.Method, r.URL)
					for k, v := range r.Header {
						log.Printf("k=%q v=%q", k, v)
					}
					b, err := ioutil.ReadAll(r.Body)
					if err != nil {
						return
					}
					log.Printf("body=%q", b)
				}),
			})
		}
	}
}

type guide struct {
	routeguide.RouteGuideServer
}

func (f *guide) ListFeatures(req *routeguide.Rectangle, srv routeguide.RouteGuide_ListFeaturesServer) error {
	for i := 0; i < itemCount; i++ {
		err := srv.Send(&routeguide.Feature{
			Name: strings.Repeat("a", itemSize),
		})
		if err != nil {
			return err
		}
	}
	return nil
}
