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

// operator-pre-inc-dec.go
package expr

// -------- pre increment term

func newPreIncTerm(tk *Token) *term {
	return &term{
		tk:       *tk,
		parent:   nil,
		children: make([]*term, 0, 1),
		position: posPrefix,
		priority: priIncDec,
		evalFunc: evalPreInc,
	}
}

func evalPreInc(ctx ExprContext, opTerm *term) (v any, err error) {
	var childValue any
	if childValue, err = opTerm.evalPrefix(ctx); err != nil {
		return
	}

	if IsInteger(childValue) && opTerm.children[0].symbol() == SymVariable {
		i := childValue.(int64) + 1
		ctx.SetVar(opTerm.children[0].source(), i)
		v = i
	} else {
		err = opTerm.errIncompatibleType(childValue)
	}
	return
}

// -------- pre decrement term

func newPreDecTerm(tk *Token) *term {
	return &term{
		tk:       *tk,
		parent:   nil,
		children: make([]*term, 0, 1),
		position: posPrefix,
		priority: priIncDec,
		evalFunc: evalPreDec,
	}
}

func evalPreDec(ctx ExprContext, opTerm *term) (v any, err error) {
	var childValue any
	if childValue, err = opTerm.evalPrefix(ctx); err != nil {
		return
	}

	if IsInteger(childValue) && opTerm.children[0].symbol() == SymVariable {
		i := childValue.(int64) - 1
		ctx.SetVar(opTerm.children[0].source(), i)
		v = i
	} else {
		err = opTerm.errIncompatibleType(childValue)
	}
	return
}

// init
func init() {
	registerTermConstructor(SymPreInc, newPreIncTerm)
	registerTermConstructor(SymPreDec, newPreDecTerm)
}
