package templates

import (
	"bytes"
	"embed"
	"kube-forge/internal/config"
	"kube-forge/internal/resources"
	"os"
	"path/filepath"
	"text/template"
)

func executeTemplateToString(template *template.Template, config *config.Config) string {
	templateResult := &bytes.Buffer{}
	err := template.Execute(templateResult, config)
	if err != nil {
		panic(err)
	}
	templateResultString := templateResult.String()
	return templateResultString
}

func getTemplateFromEmbedFSFolder(embedFS embed.FS, templateFile string) *template.Template {
	templateData, err := embedFS.ReadFile(templateFile)
	if err != nil {
		panic(err)
	}
	templateDataString := string(templateData)
	template, err := template.New("tmpl").Funcs(funcMap()).Parse(templateDataString)
	if err != nil {
		panic(err)
	}
	return template
}

func applyTemplates(templates [][2]string) {
	config := config.GetConfig()
	for _, templateData := range templates {
		var templateFile = templateData[0]
		var outFile = filepath.Join(config.WorkDir, templateData[1])

		tmpl := getTemplateFromEmbedFSFolder(resources.Templates, templateFile)

		file, err := os.Create(outFile)
		if err != nil {
			panic(err)
		}
		defer file.Close()
		err = tmpl.Execute(file, config)
		if err != nil {
			panic(err)
		}
	}
}
