// Copyright 2023 wanderer <a_mirre at utb dot cz>
// SPDX-License-Identifier: GPL-3.0-or-later

package report

import (
	_ "embed"
	"fmt"
	"log"
	"os"
	"text/template"
	"time"

	"git.dotya.ml/wanderer/math-optim/util"
)

//go:embed comparisonOfMeans.tmpl
var tmplComparisonOfMeansFile []byte

// SaveComparisonOfMeans saves each pic in the list to file, takes note of the
// saved file names.
func SaveComparisonOfMeans(p PicList, benchCount int) {
	// algos contains a title of sorts in the form "Algo vs Algo vs Algo...",
	// i.e.  p.Algo has been repurposed in this instance to contain the names
	// of all pertaining algos.
	algos := p.Algo
	texfiles := picTexFiles{Algo: "Comparison of Algo Means: " + algos}
	safeName := util.SanitiseFName(algos)
	texPicsFile := fmt.Sprintf("%spics-%s.tex", GetTexDir(), safeName)
	tmplComparisonOfMeans := template.New("comparisonofmeans")
	tmplComparisonOfMeans = template.Must(
		tmplComparisonOfMeans.Parse(string(tmplComparisonOfMeansFile)),
	)
	benchPicLists := make([]PicList, 0, benchCount)

	// split the slice to smaller, per-bench slices.
	for i := 0; i < len(p.Pics); i += benchCount {
		pL := &PicList{}
		pL.Pics = p.Pics[i : i+benchCount]
		pL.Bench = p.Pics[i].Bench
		benchPicLists = append(benchPicLists, *pL)
	}

	// make sure the output dir exists, else die early.
	if err := util.CreatePath(GetTexDir()); err != nil {
		log.Fatalln(err)
	}

	f, err := os.Create(texPicsFile)
	if err != nil {
		log.Println(err)
	}
	defer f.Close()

	err = tmplComparisonOfMeans.Execute(f, struct {
		Title      string
		Bench      string
		BenchCount int
		PicLists   []PicList
		Timestamp  time.Time
	}{
		Title:      p.Algo,
		Bench:      p.Bench,
		BenchCount: benchCount,
		PicLists:   benchPicLists,
		Timestamp:  time.Now(),
	})

	if err != nil {
		log.Println(err)
	}

	texfiles.FilePaths = []string{texPicsFile}
	allPics.TexFiles = append(allPics.TexFiles, texfiles)
}
