package eu.jonahbauer.raytracing.render.material;

import eu.jonahbauer.raytracing.math.Ray;
import eu.jonahbauer.raytracing.math.Vec3;
import eu.jonahbauer.raytracing.render.texture.Texture;
import eu.jonahbauer.raytracing.scene.HitResult;
import org.jetbrains.annotations.NotNull;

import java.util.Objects;
import java.util.Optional;
import java.util.random.RandomGenerator;

public record LambertianMaterial(@NotNull Texture texture) implements Material {
    public LambertianMaterial {
        Objects.requireNonNull(texture, "texture");
    }

    @Override
    public @NotNull Optional<ScatterResult> scatter(@NotNull Ray ray, @NotNull HitResult hit, @NotNull RandomGenerator random) {
        var newDirection = hit.normal().plus(Vec3.random(random, true));
        if (newDirection.isNearZero()) newDirection = hit.normal();

        var attenuation = texture.get(hit);
        var scattered = new Ray(hit.position(), newDirection);
        return Optional.of(new ScatterResult(scattered, attenuation));
    }
}
