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

// operator-coalesce.go
package expr

//-------- null coalesce term

func newNullCoalesceTerm(tk *Token) (inst *term) {
	return &term{
		tk:       *tk,
		children: make([]*term, 0, 2),
		position: posInfix,
		priority: priCoalesce,
		evalFunc: evalNullCoalesce,
	}
}

func evalNullCoalesce(ctx ExprContext, self *term) (v any, err error) {
	var rightValue any

	if err = self.checkOperands(); err != nil {
		return
	}

	leftTerm := self.children[0]
	if leftTerm.tk.Sym != SymVariable {
		err = leftTerm.Errorf("left operand of %q must be a variable", self.tk.source)
		return
	}

	if leftValue, exists := ctx.GetVar(leftTerm.source()); exists {
		v = leftValue
	} else if rightValue, err = self.children[1].compute(ctx); err == nil {
		v = rightValue
	}
	return
}

//-------- coalesce assign term

func newCoalesceAssignTerm(tk *Token) (inst *term) {
	return &term{
		tk:       *tk,
		children: make([]*term, 0, 2),
		position: posInfix,
		priority: priCoalesce,
		evalFunc: evalAssignCoalesce,
	}
}

func evalAssignCoalesce(ctx ExprContext, self *term) (v any, err error) {
	var rightValue any

	if err = self.checkOperands(); err != nil {
		return
	}

	leftTerm := self.children[0]
	if leftTerm.tk.Sym != SymVariable {
		err = leftTerm.Errorf("left operand of %q must be a variable", self.tk.source)
		return
	}

	if leftValue, exists := ctx.GetVar(leftTerm.source()); exists {
		v = leftValue
	} else if rightValue, err = self.children[1].compute(ctx); err == nil {
		if functor, ok := rightValue.(Functor); ok {
			//ctx.RegisterFunc(leftTerm.source(), functor, 0, -1)
			ctx.RegisterFunc(leftTerm.source(), functor, typeAny, []ExprFuncParam{
				newFuncParamFlag(paramValue, pfOptional|pfRepeat),
			})
		} else {
			v = rightValue
			ctx.UnsafeSetVar(leftTerm.source(), rightValue)
		}
	}
	return
}

// init
func init() {
	registerTermConstructor(SymDoubleQuestion, newNullCoalesceTerm)
	registerTermConstructor(SymQuestionEqual, newCoalesceAssignTerm)
}