package main

import (
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"net/http"

	"code.justin.tv/eventbus/controlplane/infrastructure/rpc"
	"code.justin.tv/eventbus/controlplane/internal/ldap/injector"
	rpcEvent "code.justin.tv/eventbus/controlplane/rpc"
)

// Use this tool locally to inject dummy events into the controlplane table

var filepath string

func init() {
	flag.StringVar(&filepath, "filepath", "./cmd/event-injector/testdata/event_types.json", "filepath of events to inject")
	flag.Parse()
}

func main() {
	ctx := context.Background()
	ldapInjector := injector.NewLDAPHeaderInjector("controlplane-updater", http.DefaultTransport)
	ldapInjector = ldapInjector.WithGroups([]string{"team-eventbus"})

	httpClient := &http.Client{
		Transport: ldapInjector,
	}
	client := rpc.NewInfrastructureProtobufClient("http://localhost:8888", httpClient)

	b, err := ioutil.ReadFile(filepath)
	if err != nil {
		panic(err)
	}

	req := &rpc.RegisterEventDefinitionsReq{}
	err = json.Unmarshal(b, req)
	if err != nil {
		panic(err)
	}

	for _, e := range req.EventDefinitions {
		fmt.Println(e.Description)
	}

	resp, err := client.RegisterEventDefinitions(ctx, req)
	if err != nil {
		panic(err)
	}

	bOut, err := json.MarshalIndent(resp, "", "  ")
	if err != nil {
		panic(err)
	}

	fetchClient := rpcEvent.NewEventStreamsProtobufClient("http://localhost:8888", httpClient)
	eventsResp, err := fetchClient.List(ctx, &rpcEvent.ListEventStreamsReq{})
	if err != nil {
		panic(err)
	}
	for _, event := range eventsResp.EventStreams {
		b, err := json.MarshalIndent(event, "", "  ")
		if err != nil {
			panic(err)
		}
		fmt.Println(string(b))
	}
	fmt.Println(string(bOut))
}
