package day08

type Node struct {
	Children []*Node
	Metadata []int
}

func (node Node) SumMetadata() int {
	sum := 0
	for _, v := range node.Metadata {
		sum += v
	}
	return sum
}

func BuildTree(data []int) *Node {
	root, _ := buildTreeR(data, 0)
	return root
}

func buildTreeR(data []int, index int) (*Node, int) {
	node := &Node{}
	numChildren := data[index]
	numMetadata := data[index+1]
	index += 2

	for i := 0; i < numChildren; i++ {
		var child *Node
		child, index = buildTreeR(data, index)
		node.Children = append(node.Children, child)
	}

	for i := 0; i < numMetadata; i++ {
		node.Metadata = append(node.Metadata, data[index+i])
	}

	return node, index + numMetadata
}