package main

import (
	"flag"
	"io"
	"log"
	"os"
	"os/signal"
	"syscall"

	"golang.org/x/net/context"
	"google.golang.org/grpc"

	"code.justin.tv/common/chitin"
	_ "code.justin.tv/common/golibs/bininfo"
	"code.justin.tv/release/trace/pbmsg"
)

var (
	serverHostPort = flag.String("server", "localhost:8080", "The server hostport")
)

func main() {
	flag.Parse()

	err := chitin.ExperimentalTraceProcessOptIn()
	if err != nil {
		log.Fatalf("trace enable err=%q", err)
	}

	conn, err := grpc.Dial(*serverHostPort, grpc.WithInsecure())
	if err != nil {
		log.Fatalf("fail to dial: %v", err)
	}
	defer conn.Close()
	client := pbmsg.NewTraceClient(conn)
	ctx, cancel := context.WithCancel(context.Background())

	log.Println("turning on signal handling")
	sigch := make(chan os.Signal, 1)
	signal.Notify(sigch, syscall.SIGINT)
	go func() {
		for _ = range sigch {
			log.Println("Canceling context...")
			cancel()
		}
	}()

	firehose, err := client.Firehose(ctx, &pbmsg.FirehoseRequest{
		Sampling: 0.01,
		Query: &pbmsg.Query{
			Comparisons: []*pbmsg.Comparison{
				&pbmsg.Comparison{
					ServiceName: &pbmsg.StringComparison{Value: "code.justin.tv/web/web"},
				},
			},
			Subqueries: []*pbmsg.Query{
				&pbmsg.Query{
					Comparisons: []*pbmsg.Comparison{
						&pbmsg.Comparison{
							ServiceName: &pbmsg.StringComparison{Value: "code.justin.tv/web/cohesion/cmd/cohesion"},
						},
					},
				},
			},
		},
	})
	if err != nil {
		log.Fatalf("%v.Firehose(_) = _, %v", client, err)
	}

	for {
		tx, err := firehose.Recv()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatalf("%v.Firehose(_) = _, %v", client, err)
		}
		log.Println(tx)
	}
}
