package smartling

import (
	"code.justin.tv/cplat/twitchling/internal/syntax"
	"code.justin.tv/cplat/twitchling/internal/syntax/ast"
)

type ValidateError struct {
	message string
}

func (e *ValidateError) Error() string {
	return e.message
}

func Validate(parseResult syntax.ParseResult) error {
	// TODO: Extend this to validate `select` when it is added.
	// When extending this for `select` the fact that plurals can be nested inside
	// `select` and `select` nested inside plurals will need to be accounted for.

	pluralCount := countPlurals(parseResult.Root())

	if pluralCount > 1 {
		return &ValidateError{
			message: "more than one plural encountered in message",
		}
	}

	return nil
}

func countPlurals(nodes []ast.Node) int {
	pluralCount := 0

	for _, node := range nodes {
		switch n := node.(type) {
		case *ast.PluralFunction:
			pluralCount++
			for _, v := range n.Variants() {
				pluralCount += countPlurals(v)
			}
		case *ast.Element:
			pluralCount += countPlurals(n.Nodes())
		}
	}

	return pluralCount
}
