package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httptest"
	"time"

	"code.justin.tv/common/chitin"
	"code.justin.tv/release/trace/rpc/alvin/restclient"
	"code.justin.tv/rhys/nursery/ext/provisioner_v1_0"
)

func main() {
	err := chitin.ExperimentalTraceProcessOptIn()
	if err != nil {
		log.Fatalf("chitin; err = %v", err)
	}

	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Printf("method=%q", r.Method)
		log.Printf("uri=%q", r.URL.Path)
		log.Printf("params=%q", r.URL.Query().Encode())
		log.Printf("url=%q", r.URL.String())
		if body, err := ioutil.ReadAll(r.Body); err != nil {
			log.Printf("body err=%q", err)
		} else {
			log.Printf("body=%q", body)
		}
		fmt.Fprintf(w, "{}")
	}))
	defer srv.Close()

	rt, _ := chitin.RoundTripper(
		context.Background(),
		&http.Transport{},
	)

	art, err := restclient.RoundTripperFromProtos(rt, []string{
		"code.justin.tv/rhys/nursery/ext/provisioner_v1_0/provisioner.proto",
	})
	if err != nil {
		log.Fatalf("RoundTripperFromFiles; err = %v", err)
	}

	target := srv.URL
	target = "https://provisioner.internal.justin.tv"
	proviz := provisioner_v1_0.NewProvisionerProtobufClient(target,
		&http.Client{Transport: art},
	)

	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	list, err := proviz.ListDevices(ctx, &provisioner_v1_0.ListDevicesRequest{
		Limit:  30,
		Filter: "trace",
	})
	if err != nil {
		log.Fatalf("ListDevices; err = %v", err)
	}

	for _, dev := range list.Device {
		log.Printf("device uuid=%q name=%q", dev.Uuid, dev.Name)
	}
}
