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

// builtins-register.go
package expr

import (
	"fmt"
)

type builtinModule struct {
	importFunc  func(ExprContext)
	description string
	imported    bool
}

func newBuiltinModule(importFunc func(ExprContext), description string) *builtinModule {
	return &builtinModule{importFunc, description, false}
}

var builtinModuleRegister map[string]*builtinModule

func RegisterBuiltinModule(name string, importFunc func(ExprContext), description string) {
	if builtinModuleRegister == nil {
		builtinModuleRegister = make(map[string]*builtinModule)
	}
	if _, exists := builtinModuleRegister[name]; exists {
		panic(fmt.Errorf("module %q already registered", name))
	}
	builtinModuleRegister[name] = newBuiltinModule(importFunc, description)
}

func IterateBuiltinModules(op func(name, description string, imported bool) bool) {
	if op != nil {
		for name, mod := range builtinModuleRegister {
			if !op(name, mod.description, mod.imported) {
				break
			}
		}
	}
}

// ----
func init() {
	if builtinModuleRegister == nil {
		builtinModuleRegister = make(map[string]*builtinModule)
	}
}
