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

// operator-length.go
package expr

//-------- length term

func newLengthTerm(tk *Token) (inst *term) {
	return &term{
		tk:       *tk,
		children: make([]*term, 0, 1),
		position: posPrefix,
		priority: priSign,
		evalFunc: evalLength,
	}
}

func evalLength(ctx ExprContext, self *term) (v any, err error) {
	var childValue any

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

	if IsList(childValue) {
		ls, _ := childValue.(*ListType)
		v = int64(len(*ls))
	} else if IsString(childValue) {
		s, _ := childValue.(string)
		v = int64(len(s))
	} else if IsDict(childValue) {
		// m, _ := childValue.(map[any]any)
		m, _ := childValue.(*DictType)
		v = int64(len(*m))
	} else if it, ok := childValue.(Iterator); ok {
		if extIt, ok := childValue.(ExtIterator); ok && extIt.HasOperation(countName) {
			count, _ := extIt.CallOperation(countName, nil)
			v, _ = ToGoInt(count, "")
		} else {
			v = int64(it.Index() + 1)
		}
	} else {
		err = self.errIncompatibleType(childValue)
	}
	return
}

// init
func init() {
	registerTermConstructor(SymHash, newLengthTerm)
}
