// Copyright 2021 by Jonathan Amsterdam. All rights reserved.

//go:build go1.16
// +build go1.16

package printsrc_test

import (
	"bytes"
	"database/sql"
	"fmt"
	"go/format"
	"log"
	"text/template"
	"time"

	"github.com/jba/printsrc"
)

// This example shows how to use printsrc along with the text/template package
// to generate a file of Go code.
func Example_template() {
	p := printsrc.NewPrinter("github.com/jba/printsrc_test")

	data := struct {
		Start   time.Time
		Strings []sql.NullString
	}{
		Start: time.Date(2021, 12, 21, 14, 32, 11, 00, time.Local),
		Strings: []sql.NullString{
			{String: "ok", Valid: true},
			{String: "", Valid: false},
		},
	}

	tmpl := template.Must(template.New("").
		Funcs(template.FuncMap{"src": p.Sprint}).
		Parse(`
		// Code generated by example_template_test.go. DO NOT EDIT.

		package example

        import (
	      "database/sql"
	      "time"
		)

		var startTime = {{.Start | src}}

		var strings = {{.Strings | src}}
	`))

	var buf bytes.Buffer
	if err := tmpl.Execute(&buf, data); err != nil {
		log.Fatal(err)
	}
	src, err := format.Source(buf.Bytes())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s", src)

	// Output:
	// // Code generated by example_template_test.go. DO NOT EDIT.
	//
	// package example
	//
	// import (
	// 	"database/sql"
	// 	"time"
	// )
	//
	// var startTime = time.Date(2021, time.December, 21, 14, 32, 11, 0, time.Local)
	//
	// var strings = []sql.NullString{
	// 	{
	// 		String: "ok",
	// 		Valid:  true,
	// 	},
	// 	{},
	// }
}
