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

// operator-length.go
package expr

//-------- builtin term

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

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

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

	count := 0
	if isList(rightValue) {
		list, _ := rightValue.([]any)
		for i, moduleSpec := range list {
			if module, ok := moduleSpec.(string); ok {
				if ImportInContext(ctx, module) {
					count++
				} else {
					err = self.Errorf("unknown module %q", module)
					break
				}
			} else {
				err = self.Errorf("expected string at item nr %d, got %T", i+1, moduleSpec)
				break
			}
		}
	} else if isString(rightValue) {
		module, _ := rightValue.(string)
		count, err = ImportInContextByGlobPattern(ctx, module)
	} else {
		err = self.errIncompatibleType(rightValue)
	}
	if err == nil {
		v = count
	}
	return
}

// init
func init() {
	registerTermConstructor(SymKwBuiltin, newBuiltinTerm)
}