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

// operator-bool.go
package expr

//-------- NOT term

func newNotTerm(tk *Token) (inst *term) {
	return &term{
		tk:       *tk,
		class:    classOperator,
		kind:     kindBool,
		children: make([]*term, 0, 1),
		position: posPrefix,
		priority: priNot,
		evalFunc: evalNot,
	}
}

func evalNot(ctx exprContext, self *term) (v any, err error) {
	var rightValue any

	if rightValue, err = self.evalPrefix(ctx); err != nil {
		return
	}

	if b, ok := toBool(rightValue); ok {
		v = !b
	} else {
		err = self.errIncompatibleType(rightValue)
	}
	return
}

//-------- AND term

func newAndTerm(tk *Token) (inst *term) {
	return &term{
		tk:       *tk,
		class:    classOperator,
		kind:     kindBool,
		children: make([]*term, 0, 2),
		position: posInfix,
		priority: priAnd,
		evalFunc: evalAnd,
	}
}

func evalAnd(ctx exprContext, self *term) (v any, err error) {
	var leftValue, rightValue any
	var leftBool, rightBool bool
	var lok, rok bool

	if leftValue, rightValue, err = self.evalInfix(ctx); err != nil {
		return
	}

	leftBool, lok = toBool(leftValue)
	rightBool, rok = toBool(rightValue)

	if lok && rok {
		v = leftBool && rightBool
	} else {
		err = self.errIncompatibleTypes(leftValue, rightValue)
	}
	return
}

//-------- OR term

func newOrTerm(tk *Token) (inst *term) {
	return &term{
		tk:       *tk,
		class:    classOperator,
		kind:     kindBool,
		children: make([]*term, 0, 2),
		position: posInfix,
		priority: priOr,
		evalFunc: evalOr,
	}
}

func evalOr(ctx exprContext, self *term) (v any, err error) {
	var leftValue, rightValue any
	var leftBool, rightBool bool
	var lok, rok bool

	if leftValue, rightValue, err = self.evalInfix(ctx); err != nil {
		return
	}

	leftBool, lok = toBool(leftValue)
	rightBool, rok = toBool(rightValue)

	if lok && rok {
		v = leftBool || rightBool
	} else {
		err = self.errIncompatibleTypes(leftValue, rightValue)
	}
	return
}

// init
func init() {
	registerTermConstructor(SymNot, newNotTerm)
	registerTermConstructor(SymAnd, newAndTerm)
	registerTermConstructor(SymOr, newOrTerm)
}