package main

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

	"github.com/jinzhu/inflection"
	"gogs.carducci-dante.gov.it/karmen/core/renderer"
	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 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
	}

	model := flag.Args()[0]

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

		funcMap := template.FuncMap{
			"query": renderer.Query,
		}

		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(name)
		data.Models = inflection.Plural(name)

		tpl.Execute(oFn, data)
	}
}
