//go:build tinywasm

package gtree

import (
	"bufio"
	"io"
)

type rootGenerator struct {
	scanner       *bufio.Scanner
	nodeGenerator *nodeGenerator
}

func newRootGenerator(r io.Reader) *rootGenerator {
	return &rootGenerator{
		scanner:       bufio.NewScanner(r),
		nodeGenerator: newNodeGenerator(),
	}
}

func (rg *rootGenerator) generate() ([]*Node, error) {
	var (
		stack *stack
		roots []*Node
	)

	for rg.scanner.Scan() {
		currentNode, err := rg.nodeGenerator.generate(rg.scanner.Text())
		if err != nil {
			return nil, err
		}
		if currentNode == nil {
			continue
		}

		if currentNode.isRoot() {
			roots = append(roots, currentNode)
			stack = newStack()
			stack.push(currentNode)
			continue
		}

		if stack == nil {
			return nil, errNilStack
		}

		stack.dfs(currentNode)
	}

	return roots, rg.scanner.Err()
}
