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

// builtin-import.go
package expr

import (
	"io"
	"os"
)

func importFunc(ctx ExprContext, name string, args map[string]any) (result any, err error) {
	return importGeneral(ctx, name, args)
}

func importAllFunc(ctx ExprContext, name string, args map[string]any) (result any, err error) {
	CtrlEnable(ctx, control_export_all)
	return importGeneral(ctx, name, args)
}

func importGeneral(ctx ExprContext, name string, args map[string]any) (result any, err error) {
	dirList := buildSearchDirList("sources", ENV_EXPR_SOURCE_PATH)
	if v, exists := args[ParamFilepath]; exists && v != nil {
		argv := v.([]any)
		result, err = doImport(ctx, name, dirList, NewArrayIterator(argv))
	}
	return
}

func doImport(ctx ExprContext, name string, dirList []string, it Iterator) (result any, err error) {
	var v any
	var sourceFilepath string

	for v, err = it.Next(); err == nil; v, err = it.Next() {
		if err = checkStringParamExpected(name, v, it.Index()); err != nil {
			break
		}
		if sourceFilepath, err = makeFilepath(v.(string), dirList); err != nil {
			break
		}
		var file *os.File
		if file, err = os.Open(sourceFilepath); err == nil {
			defer file.Close()
			var expr *ast
			scanner := NewScanner(file, DefaultTranslations())
			parser := NewParser()
			if expr, err = parser.parseGeneral(scanner, true, true); err == nil {
				result, err = expr.Eval(ctx)
			}
			if err != nil {
				break
			}
		} else {
			break
		}
	}
	if err != nil {
		if err == io.EOF {
			err = nil
		} else {
			result = nil
		}
	}
	return
}

func ImportImportFuncs(ctx ExprContext) {
	ctx.RegisterFunc("import", NewGolangFunctor(importFunc), TypeAny, []ExprFuncParam{
		NewFuncParamFlag(ParamFilepath, PfRepeat),
	})
	ctx.RegisterFunc("importAll", NewGolangFunctor(importAllFunc), TypeAny, []ExprFuncParam{
		NewFuncParamFlag(ParamFilepath, PfRepeat),
	})
}

func init() {
	RegisterBuiltinModule("import", ImportImportFuncs, "Functions import() and include()")
}
