// 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 []any) (result any, err error) {
	var n int
	if n, err = fmt.Fprint(getStdout(ctx), args...); err == nil {
		result = int64(n)
	}
	return
}

func printLnFunc(ctx ExprContext, name string, args []any) (result any, err error) {
	var n int
	if n, err = fmt.Fprintln(getStdout(ctx), args...); err == nil {
		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")
}
