package renderer

import (
	"git.tuxpa.in/a/nori"
	"image"
	"image/color/palette"
	"image/draw"
	"image/gif"
)

func newRenderGifFunc(gif *gif.GIF) nori.RenderFunc {
	return func(img image.Image, delay int) {
		i := image.NewPaletted(img.Bounds(), palette.Plan9)
		draw.Draw(i, img.Bounds(), img, img.Bounds().Min, draw.Over)

		gif.Image = append(gif.Image, i)
		gif.Delay = append(gif.Delay, delay)
	}
}

func RenderAnimationGif(n *nori.Nori, i int) (*gif.GIF, error) {
	gif := &gif.GIF{
		Image:     make([]*image.Paletted, 0),
		Delay:     make([]int, 0),
		LoopCount: 0,
	}
	err := nori.RenderAnimation(n, i, newRenderGifFunc(gif))
	if err != nil {
		return nil, err
	}
	return gif, nil
}
