package assets

import (
	"embed"
	"image"
	_ "image/png"
	"log"
	"log/slog"
	"os"
	"path/filepath"
	"strings"

	"github.com/hajimehoshi/ebiten/v2"
)

// Maps image name to image data
type AssetRegistry map[string]*ebiten.Image

//go:embed sprites/*.png fonts/*.ttf levels/*.ldtk
var assetfs embed.FS

var Assets = LoadImages("sprites")

func LoadImages(dir string) AssetRegistry {
	images := AssetRegistry{}

	// we use embed.FS to iterate over all files in ./assets/
	entries, err := assetfs.ReadDir(dir)
	if err != nil {
		log.Fatalf("failed to read assets dir %s: %s", dir, err)
	}

	for _, imagefile := range entries {
		path := filepath.Join("assets", dir, imagefile.Name())
		fd, err := os.Open(path)
		if err != nil {
			log.Fatalf("failed to open image file %s: %s", imagefile.Name(), err)
		}
		defer fd.Close()

		name := strings.TrimSuffix(imagefile.Name(), ".png")

		img, _, err := image.Decode(fd)
		if err != nil {
			log.Fatalf("failed to decode image %s: %s", imagefile.Name(), err)
		}

		images[name] = ebiten.NewImageFromImage(img)

		slog.Debug("loaded asset", "path", path)
	}

	return images
}
