package inout

import (
	"bytes"
	"fmt"
	"net/http"
	"os"
	"text/template"
)

func getFuncMap() template.FuncMap {
	funcMap := template.FuncMap{
		"showFile":     showFile,
		"genSeriesInt": genSeriesInt,
	}
	return funcMap
}

func genSeriesInt(start, stop int64) []int64 {
	values := make([]int64, 0)
	for i := start; i <= stop; i++ {
		values = append(values, i)
	}
	return values
}

func showFile(tmpl string) string {
	data, err := os.ReadFile(tmpl)
	if err != nil {
		return fmt.Sprintf("%+v", err)
	}
	return string(data)
}

func ParseTemplate(file string, input any) ([]byte, int) {
	var buff bytes.Buffer
	b, err := os.ReadFile(file)
	if err != nil {
		return fmt.Appendf(nil, "%+v", err), http.StatusInternalServerError
	}
	tmpl, err := template.New("parse").Funcs(getFuncMap()).Parse(string(b))
	if err != nil {
		return fmt.Appendf(nil, "%+v", err), http.StatusInternalServerError
	}
	err = tmpl.Execute(&buff, input)
	if err != nil {
		return fmt.Appendf(nil, "%+v", err), http.StatusInternalServerError
	}
	return buff.Bytes(), http.StatusOK
}
