package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"text/template"

	"github.com/jinzhu/inflection"
	tpl_util "gogs.carducci-dante.gov.it/karmen/util/template"
)

var (
	fnPatterns = map[string]string{
		"all":        "%s",
		"show":       "%s_show",
		"add_update": "%s_add_update",
	}
)

func toUpper(str string) string {
	return strings.Title(str)
}

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
		flag.PrintDefaults()
	}
	outDir := flag.String("outdir", "./templates", "Output directory")
	tplDir := flag.String("tpldir", "./generator/templates", "Generator template directory")
	flag.Parse()

	if len(flag.Args()) == 0 {
		flag.Usage()
		return
	}

	funcMap := template.FuncMap{
		"toUpper": toUpper,
	}

	model := flag.Args()[0]

	for tplName, pattern := range fnPatterns {
		name := fmt.Sprintf(pattern, model)

		tpl, err := tpl_util.LoadTextTemplate(filepath.Join(*tplDir, tplName+".tpl"), funcMap)
		if err != nil {
			panic(err)
		}
		filename := filepath.Join(*outDir, name+".html.tpl")
		oFn, err := os.Create(filename)
		if err != nil {
			panic(err)
		}
		defer oFn.Close()

		log.Printf("Generating html template %s for model %s...", filename, name)

		var data struct {
			Model  string
			Models string
		}

		data.Model = inflection.Singular(model)
		data.Models = inflection.Plural(model)

		err = tpl.Execute(oFn, data)
		if err != nil {
			panic(err)
		}
	}
}
