package main

import (
	"bytes"
	"fmt"
	"strings"

	"code.justin.tv/release/trace/pbmsg"
)

type edge struct {
	src, dst string
}
type graph map[edge]int

func (g graph) addCall(client string, call *pbmsg.Call) {
	service := call.GetSvc().GetName()
	if service == "" {
		service = call.GetRequestSentTo()
	}

	g.addEdge(client, service)

	for _, sc := range call.GetSubcalls() {
		g.addCall(service, sc)
	}
}

func (g graph) addEdge(src, dst string) {
	src = strings.TrimPrefix(src, "code.justin.tv/")
	dst = strings.TrimPrefix(dst, "code.justin.tv/")
	if src == "" {
		src = "unknown"
	}
	if dst == "" {
		dst = "unknown"
	}
	g[edge{src, dst}] += 1
}

func (g graph) String() string {
	s := new(bytes.Buffer)
	s.WriteString("strict digraph {\n")
	for edge, n := range g {
		fmt.Fprintf(s, "  %q -> %q  [weight=%d]\n", edge.src, edge.dst, n)
	}
	s.WriteString("}")
	return s.String()
}
