// Copyright (c) 2024-2026 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.

// operator-iter-value.go
package expr

import (
	"git.portale-stac.it/go-pkg/expr/kern"
	"git.portale-stac.it/go-pkg/expr/scan"
	"git.portale-stac.it/go-pkg/expr/sym"
)

//-------- iter value term

func newIterValueTerm(tk *scan.Token) (inst *scan.Term) {
	return &scan.Term{
		Tk:       *tk,
		Children: make([]*scan.Term, 0, 1),
		Position: scan.PosPrefix,
		Priority: scan.PriDereference,
		EvalFunc: evalIterValue,
	}
}

func evalIterValue(ctx kern.ExprContext, opTerm *scan.Term) (v any, err error) {
	var childValue any

	if childValue, err = opTerm.EvalPrefix(ctx); err != nil {
		return
	}

	if it, ok := childValue.(kern.Iterator); ok {
		v, err = it.Current()
	} else {
		err = opTerm.ErrIncompatiblePrefixPostfixType(childValue)
	}
	return
}

// init
func init() {
	//	registerTermConstructor(SymOpenClosedRound, newIterValueTerm)
	scan.RegisterTermConstructor(sym.SymDereference, newIterValueTerm)
}
