package template

import (
	"crypto/sha1"
	"fmt"
	"io/ioutil"
	"text/template"
)

func LoadTextTemplate(filename string, funcMap ...template.FuncMap) (*template.Template, error) {
	var (
		tpl *template.Template
		err error
	)
	content, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	if len(funcMap) > 0 {
		tpl, err = template.New(filename).Funcs(funcMap[0]).Parse(string(content))
		if err != nil {
			return nil, err
		}
	} else {
		tpl, err = template.New(filename).Parse(string(content))
		if err != nil {
			return nil, err
		}
	}
	return tpl, nil
}

func LoadTextTemplateFromString(content string, funcMap ...template.FuncMap) (*template.Template, error) {
	var (
		tpl *template.Template
		err error
	)

	h := sha1.New()
	h.Write([]byte(content))

	name := fmt.Sprintf("%x", h.Sum(nil))

	if len(funcMap) > 0 {
		tpl, err = template.New(name).Funcs(funcMap[0]).Parse(content)
		if err != nil {
			return nil, err
		}
	} else {
		tpl, err = template.New(name).Parse(content)
		if err != nil {
			return nil, err
		}
	}
	return tpl, nil
}
