package assetstore

import (
	"code.ur.gs/lupine/ordoor/internal/idx"
)

type Animation struct {
	Frames []*Sprite
}

func (a *AssetStore) AnimationsIndex() (*idx.Idx, error) {
	if a.idx != nil {
		return a.idx, nil
	}

	filename, err := a.lookup("WarHammer", "idx", "Idx")
	if err != nil {
		return nil, err
	}

	idx, err := idx.Load(filename)
	if err != nil {
		return nil, err
	}

	a.idx = idx
	return idx, nil
}

func (a *AssetStore) AnimationsObject() (*Object, error) {
	if a.aniObj != nil {
		return a.aniObj, nil
	}

	filename, err := a.lookup("WarHammer", "ani", "Anim")
	if err != nil {
		return nil, err
	}

	obj, err := a.ObjectByPath(filename)
	if err != nil {
		return nil, err
	}

	a.aniObj = obj
	return obj, nil
}

func (a *AssetStore) Animation(groupIdx, recIdx int) (*Animation, error) {
	idx, err := a.AnimationsIndex()
	if err != nil {
		return nil, err
	}

	obj, err := a.AnimationsObject()
	if err != nil {
		return nil, err
	}

	group := idx.Groups[groupIdx]
	if group.Spec.Count == 0 {
		return &Animation{}, nil
	}

	//	rec := group.Records[recIdx]
	det := group.Details[recIdx]

	first := int(group.Spec.SpriteIdx) + int(det.FirstSprite)
	last := int(group.Spec.SpriteIdx) + int(det.LastSprite)
	count := last - first + 1

	sprites, err := obj.Sprites(first, count)
	if err != nil {
		return nil, err
	}

	return &Animation{Frames: sprites}, nil
}
