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

// operator-insert.go
package expr

//-------- insert term

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

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

func evalInsert(ctx ExprContext, opTerm *term) (v any, err error) {
	var leftValue, rightValue any

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

	if IsList(rightValue) {
		list, _ := rightValue.(*ListType)
		newList := append(ListType{leftValue}, *list...)
		v = &newList
		if opTerm.children[1].symbol() == SymVariable {
			ctx.UnsafeSetVar(opTerm.children[1].source(), v)
		}
	} else {
		err = opTerm.errIncompatibleTypes(leftValue, rightValue)
	}
	return
}

func evalAppend(ctx ExprContext, opTerm *term) (v any, err error) {
	var leftValue, rightValue any

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

	if IsList(leftValue) {
		list, _ := leftValue.(*ListType)
		newList := append(*list, rightValue)
		v = &newList
		if opTerm.children[0].symbol() == SymVariable {
			ctx.UnsafeSetVar(opTerm.children[0].source(), v)
		}
	} else {
		err = opTerm.errIncompatibleTypes(leftValue, rightValue)
	}
	return
}

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

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

// 	if IsList(leftValue) {
// 		list, _ := leftValue.(*ListType)
// 		newList := append(*list, rightValue)
// 		v = &newList
// 		if
// 	} else {
// 		err = self.errIncompatibleTypes(leftValue, rightValue)
// 	}
// 	return
// }

// init
func init() {
	registerTermConstructor(SymInsert, newInsertTerm)
	registerTermConstructor(SymAppend, newAppendTerm)
}
