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

// operator-builtin.go
package expr

import "io"

//-------- 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, opTerm *term) (v any, err error) {
	var childValue any

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

	count := 0
	if IsString(childValue) {
		module, _ := childValue.(string)
		count, err = ImportInContextByGlobPattern(module)
	} else {
		var moduleSpec any
		it := NewAnyIterator(childValue)
		for moduleSpec, err = it.Next(); err == nil; moduleSpec, err = it.Next() {
			if module, ok := moduleSpec.(string); ok {
				if ImportInContext(module) {
					count++
				} else {
					err = opTerm.Errorf("unknown builtin module %q", module)
					break
				}
			} else {
				err = opTerm.Errorf("expected string at item nr %d, got %s", it.Index()+1, TypeName(moduleSpec))
				break
			}
		}
		if err == io.EOF {
			err = nil
		}
	}
	if err == nil {
		v = int64(count)
	}
	return
}

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