// Copyright ©2019 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build ignore

package main

import (
	"bytes"
	"go/ast"
	"go/format"
	"go/parser"
	"go/token"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
	"text/template"
)

const definedTemplate = `// Code generated by "go generate gonum.org/v1/gonum/unit/constant”; DO NOT EDIT.

// Copyright ©2019 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build ignore

package main

import "gonum.org/v1/gonum/unit"

var definedTypes = []struct{
	unit unit.Uniter
	name string
}{
{{range .}}	{unit: unit.{{.}}(1), name: "unit.{{.}}"{{"}"}},
{{end}}}

func definedEquivalentOf(q unit.Uniter) string {
	for _, u := range definedTypes {
		if unit.DimensionsMatch(q, u.unit) {
			return u.name
		}
	}
	return ""
}
`

var defined = template.Must(template.New("defined").Parse(definedTemplate))

func main() {
	names, err := filepath.Glob("../*.go")
	if err != nil {
		log.Fatal(err)
	}

	var units []string
	fset := token.NewFileSet()
	for _, fn := range names {
		if strings.Contains(fn, "_test") {
			continue
		}
		b, err := ioutil.ReadFile(fn)
		if bytes.Contains(b, []byte("+build ignore")) {
			continue
		}
		f, err := parser.ParseFile(fset, fn, nil, 0)
		if err != nil {
			log.Fatal("failed to parse %q: %v", fn, err) // parse error
		}
		if f.Name.Name != "unit" {
			log.Fatalf("not parsing unit package: %q", f.Name.Name)
		}
		for _, d := range f.Decls {
			if decl, ok := d.(*ast.GenDecl); ok {
				for _, s := range decl.Specs {
					if ts, ok := s.(*ast.TypeSpec); ok {
						if id, ok := ts.Type.(*ast.Ident); !ok || id.Name != "float64" {
							continue
						}
						units = append(units, ts.Name.Name)
					}
				}
			}
		}
	}

	f, err := os.Create("defined_types.go")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	var buf bytes.Buffer
	err = defined.Execute(&buf, units)
	if err != nil {
		log.Fatal(err)
	}

	b, err := format.Source(buf.Bytes())
	if err != nil {
		f.Write(buf.Bytes()) // This is here to debug bad format.
		log.Fatalf("error formatting %q: %s", f.Name(), err)
	}

	f.Write(b)
}
