package renderer_test

import (
	"bytes"
	"fmt"
	"git.tuxpa.in/a/nori"
	"git.tuxpa.in/a/nori/renderer"
	"git.tuxpa.in/a/zlog/log"
	"image/gif"
	"os"
	"strings"
	"testing"
)

func TestMakeGif1(t *testing.T) {
	nori, err := nori.FromFile("../render_test/CharCreateNSelectUI.bac")
	if err != nil {
		t.Errorf("decode: %s", err)
	}
	t.Logf("\n nori: %+v\n gawi: %+v", nori, nori.Gawi)

	err = writeGif(nori, "charcreate")
	if err != nil {
		t.Errorf("export: %s", err)
	}
}

func writeGif(n *nori.Nori, name string) error {
	postfix := ".example"
	out := new(bytes.Buffer)
	os.MkdirAll(fmt.Sprintf("../render_test/%s%s", name, postfix), 0740)
	for i := range n.Animations {
		g, err := renderer.RenderAnimationGif(n, i)
		if err != nil {
			if strings.Contains(err.Error(), "no frame") {
				continue
			}
			return err
		}
		err = gif.EncodeAll(out, g)
		if err != nil {
			log.Errorf("EncodeAll failed for frame %d, skipping: %s", i, err)
			continue
		}
		err = os.WriteFile(fmt.Sprintf("../render_test/%s%s/animation_%d.gif", name, postfix, i), out.Bytes(), 0740)
		if err != nil {
			return err
		}
		out.Reset()
	}
	return nil
}
