package main

import (
	"bytes"
	"fmt"
	"io"
	"log"

	yaml "gopkg.in/yaml.v2"
	"novit.tech/direktil/local-server/pkg/clustersconfig"
)

func (ctx *renderContext) renderStaticPods() (pods []namePod) {
	if ctx.Host.StaticPods == "" {
		return
	}

	staticPods, ok := src.StaticPods[ctx.Host.StaticPods]
	if !ok {
		log.Fatalf("no static pods template named %q", ctx.Host.StaticPods)
	}

	// render static pods
	parts := bytes.Split(ctx.renderHostTemplates("static-pods", staticPods), []byte("\n---\n"))
	for _, part := range parts {
		buf := bytes.NewBuffer(part)
		dec := yaml.NewDecoder(buf)

		for n := 0; ; n++ {
			str := buf.String()

			podMap := map[string]any{}
			err := dec.Decode(podMap)

			if err == io.EOF {
				break
			} else if err != nil {
				log.Fatalf("static pod %d: failed to parse: %v\n%s", n, err, str)
			}

			if len(podMap) == 0 {
				continue
			}

			if podMap["metadata"] == nil {
				log.Fatalf("static pod %d: no metadata\n%s", n, buf.String())
			}

			md := podMap["metadata"].(map[any]any)

			namespace := md["namespace"].(string)
			name := md["name"].(string)

			pods = append(pods, namePod{namespace, name, podMap})
		}
	}

	return
}

func (ctx *renderContext) renderHostTemplates(setName string,
	templates []*clustersconfig.Template) []byte {

	log.Print("rendering host templates in ", setName)

	buf := bytes.NewBuffer(make([]byte, 0, 16<<10))

	for _, t := range templates {
		log.Print("- template: ", setName, ": ", t.Name)
		fmt.Fprintf(buf, "---\n# %s: %s\n", setName, t.Name)

		ctx.renderConfigTo(buf, t)
		fmt.Fprintln(buf)
	}

	return buf.Bytes()
}
