package eu.jonahbauer.raytracing.render.texture;

import eu.jonahbauer.raytracing.math.Vec3;
import eu.jonahbauer.raytracing.render.canvas.Image;
import org.jetbrains.annotations.NotNull;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Objects;

public record ImageTexture(@NotNull Image image) implements Texture {

    public ImageTexture {
        Objects.requireNonNull(image, "image");
    }

    public ImageTexture(@NotNull BufferedImage image) {
        this(new Image(image));
    }

    public ImageTexture(@NotNull String path) {
        this(read(path));
    }

    private static @NotNull BufferedImage read(@NotNull String path) {
        try (var in = Objects.requireNonNull(ImageTexture.class.getResourceAsStream(path))) {
            return ImageIO.read(in);
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    }

    @Override
    public @NotNull Color get(double u, double v, @NotNull Vec3 p) {
        u = Math.clamp(u, 0, 1);
        v = 1 - Math.clamp(v, 0, 1);
        int x = (int) (u * (image.getWidth() - 1));
        int y = (int) (v * (image.getHeight() - 1));
        return image.get(x, y);
    }
}
