package definitions

import (
	"github.com/Xuanwo/gg"
	"github.com/Xuanwo/templateutils"
	log "github.com/sirupsen/logrus"
)

func GeneratePair(path string) {
	g := gg.New()
	f := g.NewGroup()
	f.AddLineComment("Code generated by go generate cmd/definitions; DO NOT EDIT.")
	f.AddPackage("pairs")
	f.NewImport().
		AddPath("github.com/beyondstorage/go-storage/v5/types")

	ps := SortPairs(PairArray)

	for _, v := range ps {
		pname := templateutils.ToPascal(v.Name)

		f.AddLineComment(`With%s will apply %s value to Options.

%s %s`, pname, v.Name, pname, v.Description)
		xfn := f.NewFunction("With" + pname)
		xfn.AddResult("p", "types.Pair")

		// If value type is bool, we don't need to accept parameters.
		if v.Type.Name == "bool" {
			xfn.AddBody(
				gg.Return(
					gg.Value("types.Pair").
						AddField("Key", gg.Lit(v.Name)).
						AddField("Value", "true")))
			continue
		}

		xfn.AddParameter("v", v.Type.FullName("pairs"))
		xfn.AddBody(
			gg.Return(
				gg.Value("types.Pair").
					AddField("Key", gg.Lit(v.Name)).
					AddField("Value", "v")))
	}

	err := g.WriteFile(path)
	if err != nil {
		log.Fatalf("generate to %s: %v", path, err)
	}
}
