package renderer

import (
	"git.tuxpa.in/a/nori"
	"gitlab.com/gfxlabs/gfximg/apng"
	"image"
	"strings"
)

func newRenderApngFunc(a *apng.APNG) nori.RenderFunc {
	return func(img image.Image, delay int) {
		fr := apng.Frame{
			Image:            img,
			DelayDenominator: 1000,
		}
		if delay != 0 {
			fr.DelayNumerator = uint16(delay)
		}
		a.Frames = append(a.Frames, fr)
	}
}

func RenderAnimationsApng(n *nori.Nori) ([]*apng.APNG, error) {
	apngs := make([]*apng.APNG, 0, len(n.Animations))
	for i := range n.Animations {
		a, err := RenderAnimationApng(n, i)
		if err != nil {
			if strings.Contains(err.Error(), "no frame") {
				continue
			}
			return nil, err
		}
		apngs = append(apngs, a)
	}
	return apngs, nil
}

func RenderAnimationApng(n *nori.Nori, i int) (*apng.APNG, error) {
	a := &apng.APNG{
		Frames: make([]apng.Frame, 0, len(n.Gawi.Images)),
	}
	err := nori.RenderAnimation(n, i, newRenderApngFunc(a))
	if err != nil {
		return nil, err
	}
	return a, nil
}
