package cz.jzitnik.game;

import cz.jzitnik.annotations.Dependency;
import cz.jzitnik.annotations.injectors.InjectDependency;
import lombok.AllArgsConstructor;
import lombok.Getter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

@Dependency
public class ResourceManager {
    @InjectDependency
    private ClassLoader classLoader;

    @AllArgsConstructor
    @Getter
    public enum Resource {
        ROOM1("rooms/1.png"),
        ROOM2("rooms/2.png"),
        ROOM3("rooms/3.png"),
        ROOM4("rooms/4.png"),
        ROOM_FROZEN("rooms/frozen.png"),

        PLAYER_FRONT("player/front.png"),
        PLAYER_BACK("player/back.png"),
        PLAYER_LEFT("player/left.png"),
        PLAYER_RIGHT("player/right.png"),

        CHEST("chest.png"),

        WOODEN_SWORD("tools/wooden_sword.png"),

        DOORS("rooms/doors.png");

        private final String path;
    }

    private final HashMap<Resource, BufferedImage> resourceCache = new HashMap<>();

    public BufferedImage getResource(Resource resource) {
        if (resourceCache.containsKey(resource)) {
            return resourceCache.get(resource);
        }

        InputStream is = classLoader.getResourceAsStream("textures/" + resource.getPath());
        if (is == null) {
            throw new RuntimeException("Image not found in resources!");
        }

        try {
            BufferedImage image = ImageIO.read(is);
            resourceCache.put(resource, image);
            return image;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public InputStream getResourceAsStream(String path) {
        return classLoader.getResourceAsStream(path);
    }
}
