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

// operator-sign.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"
	"git.portale-stac.it/go-pkg/expr/types"
	"git.portale-stac.it/go-pkg/expr/types/float"
)

//-------- plus sign term

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

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

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

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

	if float.IsFloat(rightValue) {
		if opTerm.Tk.Sym == sym.SymChangeSign {
			f, _ := rightValue.(float64)
			v = -f
		} else {
			v = rightValue
		}
	} else if types.IsInteger(rightValue) {
		if opTerm.Tk.Sym == sym.SymChangeSign {
			i, _ := rightValue.(int64)
			v = -i
		} else {
			v = rightValue
		}
	} else {
		err = opTerm.ErrIncompatiblePrefixPostfixType(rightValue)
	}
	return
}

// init
func init() {
	scan.RegisterTermConstructor(sym.SymUnchangeSign, newPlusSignTerm)
	scan.RegisterTermConstructor(sym.SymChangeSign, newMinusSignTerm)
}
