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

// global-context.go
package expr

import (
	"path/filepath"
	"strings"

	"git.portale-stac.it/go-pkg/expr/kern"
	"git.portale-stac.it/go-pkg/expr/types/boolean"
)

//var globalCtx *SimpleStore

func ImportInContext(ctx kern.ExprContext, name string) (exists bool) {
	if globalCtx := ctx.GetGlobal(); globalCtx != nil {
		var mod *builtinModule
		if mod, exists = builtinModuleRegister[name]; exists {
			mod.importFunc(globalCtx)
			mod.imported = true
		}
	}
	return
}

func ImportInContextByGlobPattern(ctx kern.ExprContext, pattern string) (count int, err error) {
	if globalCtx := ctx.GetGlobal(); globalCtx != nil {
		var matched bool
		for name, mod := range builtinModuleRegister {
			if matched, err = filepath.Match(pattern, name); err == nil {
				if matched {
					count++
					mod.importFunc(globalCtx)
					mod.imported = true
				}
			} else {
				break
			}
		}
	}
	return
}

func fixCtrlVar(name string) string {
	if !strings.HasPrefix(name, "_") {
		name = "_" + name
	}
	return name
}

func GlobalCtrlSet(ctx kern.ExprContext, name string, newValue any) (currentValue any) {
	if globalCtx := ctx.GetGlobal(); globalCtx != nil {
		name = fixCtrlVar(name)
		currentValue, _ = globalCtx.GetVar(name)
		globalCtx.SetVar(name, newValue)
	}
	return currentValue
}

func GlobalCtrlGet(ctx kern.ExprContext, name string) (currentValue any) {
	if globalCtx := ctx.GetGlobal(); globalCtx != nil {
		name = fixCtrlVar(name)
		currentValue, _ = globalCtx.GetVar(name)
	}
	return currentValue
}

func CtrlEnable(ctx kern.ExprContext, name string) (currentStatus bool) {
	name = fixCtrlVar(name)
	if v, exists := ctx.GetVar(name); exists && boolean.IsBool(v) {
		currentStatus, _ = v.(bool)
	}

	ctx.SetVar(name, true)
	return currentStatus
}

func CtrlDisable(ctx kern.ExprContext, name string) (currentStatus bool) {
	name = fixCtrlVar(name)
	if v, exists := ctx.GetVar(name); exists && boolean.IsBool(v) {
		currentStatus, _ = v.(bool)
	}

	ctx.SetVar(name, false)
	return currentStatus
}

// func CtrlIsEnabled(ctx ExprContext, name string) (status bool) {
// 	var v any
// 	var exists bool

// 	if !strings.HasPrefix(name, "_") {
// 		name = "_" + name
// 	}

// 	if v, exists = ctx.GetVar(name); !exists {
// 		v, exists = globalCtx.GetVar(name)
// 	}

// 	if exists {
// 		if b, ok := v.(bool); ok {
// 			status = b
// 		}
// 	}
// 	return
// }

func getControlString(ctx kern.ExprContext, name string) (s string, exists bool) {
	if globalCtx := ctx.GetGlobal(); globalCtx != nil {
		var v any
		if v, exists = globalCtx.GetVar(name); exists {
			s, exists = v.(string)
		}
	}
	return
}

func InitGlobal() (ctx kern.ExprContext) {
	ctx = NewSimpleStoreWithoutGlobalContext()
	kern.InitDefaultVars(ctx)
	ImportBuiltinsFuncs(ctx)
	return
}
