package pgs

import (
	"io"
	"os"

	"github.com/spf13/afero"
)

// An InitOption modifies the behavior of a Generator at initialization.
type InitOption func(g *Generator)

// ParamMutator is a method that modifies Parameters p in-place. These are
// typically applied before code generation begins, and configurable via the
// MutateParams InitOption.
type ParamMutator func(p Parameters)

// ProtocInput changes the input io.Reader source. This value is where the
// serialized CodeGeneratorRequest is received from protoc. By default,
// os.Stdin is used.
func ProtocInput(r io.Reader) InitOption { return func(g *Generator) { g.in = r } }

// ProtocOutput changes the output io.Writer destination. This value is where
// the serialized CodeGeneratorResponse is sent to protoc. By default,
// os.Stdout is used.
func ProtocOutput(w io.Writer) InitOption { return func(g *Generator) { g.out = w } }

// DebugMode enables verbose logging for module development and debugging.
func DebugMode() InitOption { return func(g *Generator) { g.debug = true } }

// DebugEnv enables verbose logging only if the passed in environment variable
// is non-empty.
func DebugEnv(f string) InitOption { return func(g *Generator) { g.debug = os.Getenv(f) != "" } }

// MutateParams applies pm to the parameters passed in from protoc.
func MutateParams(pm ...ParamMutator) InitOption {
	return func(g *Generator) { g.paramMutators = append(g.paramMutators, pm...) }
}

// FileSystem overrides the default file system used to write Artifacts to
// disk. By default, the OS's file system is used. This option currently only
// impacts CustomFile and CustomTemplateFile artifacts generated by modules.
func FileSystem(fs afero.Fs) InitOption { return func(g *Generator) { g.persister.SetFS(fs) } }

// BiDirectional instructs the Generator to build the AST graph in both
// directions (ie, accessing dependents of an entity, not just dependencies).
func BiDirectional() InitOption {
	return func(g *Generator) { g.workflow = &onceWorkflow{workflow: &standardWorkflow{BiDi: true}} }
}

// SupportedFeatures allows defining protoc features to enable / disable.
// See: https://github.com/protocolbuffers/protobuf/blob/v3.17.0/docs/implementing_proto3_presence.md#signaling-that-your-code-generator-supports-proto3-optional
func SupportedFeatures(feat *uint64) InitOption {
	return func(g *Generator) {
		g.persister.SetSupportedFeatures(feat)
	}
}
