package analysis

import (
	"code.justin.tv/release/trace/analysis/callgraph"
	"code.justin.tv/release/trace/analysis/tx"
)

// Split splits the root nodes of a TransactionSet into smaller sets, grouped by common
// values of a string. The new TransactionSets are made in memory.
func Split(txs tx.TransactionSet, dim callgraph.StringDimension) map[string]tx.TransactionSet {
	groups := make(map[string]tx.TransactionSet)
	var label string
	for _, t := range txs.All() {
		label = t.Root.Label(dim)
		groupTxs, ok := groups[label]
		if !ok {
			groupTxs = tx.NewInMemoryTransactionSet()
			groups[label] = groupTxs
		}
		groupTxs.Add(t)
	}
	return groups
}

func SplitBySignature(txs tx.TransactionSet) map[string]*tx.SignatureSet {
	bySig := Split(txs, callgraph.Signature)
	out := make(map[string]*tx.SignatureSet)
	for sig, txSet := range bySig {
		out[sig] = tx.NewSignatureSet(sig, txSet)
	}
	return out
}

func SplitByServer(txs tx.TransactionSet) map[string]tx.TransactionSet {
	return Split(txs, callgraph.Server)
}
