package assets

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

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

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

//go:embed levels/*.lvl sprites/*.png
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 _, entry := range entries {
		fmt.Println(entry.Name())
	}

	for _, imagefile := range entries {
		path := filepath.Join("assets", dir, imagefile.Name())
		fmt.Printf("LOADING %s ... ", path)
		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)
		fmt.Printf("done\n")
	}

	return images
}
