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

// builtin-fmt.go
package expr

import (
	"fmt"
	"io"
	"os"
)

func getStdout(ctx ExprContext) io.Writer {
	var w io.Writer
	if wany, exists := ctx.GetVar(ControlStdout); exists && wany != nil {
		w, _ = wany.(io.Writer)
	}
	if w == nil {
		w = os.Stdout
	}
	return w
}

func printFunc(ctx ExprContext, name string, args map[string]any) (result any, err error) {
	var n int = 0
	if v, exists := args[ParamItem]; exists && v != nil {
		argv := v.([]any)
		n, err = fmt.Fprint(getStdout(ctx), argv...)
	}
	result = int64(n)
	return
}

func printLnFunc(ctx ExprContext, name string, args map[string]any) (result any, err error) {
	var n int = 0
	if v, exists := args[ParamItem]; exists && v != nil {
		argv := v.([]any)
		n, err = fmt.Fprintln(getStdout(ctx), argv...)
	} else {
		n, err = fmt.Fprintln(getStdout(ctx))
	}
	result = int64(n)
	return
}

func ImportFmtFuncs(ctx ExprContext) {
	ctx.RegisterFunc("print", NewGolangFunctor(printFunc), TypeInt, []ExprFuncParam{
		NewFuncParamFlag(ParamItem, PfRepeat),
	})
	ctx.RegisterFunc("println", NewGolangFunctor(printLnFunc), TypeInt, []ExprFuncParam{
		NewFuncParamFlag(ParamItem, PfRepeat),
	})
}

func init() {
	RegisterBuiltinModule("fmt", ImportFmtFuncs, "String and console formatting functions")
}
