package pathtracing.pbr;

import basics.math.algebra.Basis;
import basics.math.algebra.Ray;
import basics.math.algebra.Vector;
import optics.light.Color;
import pathtracing.Pathtracer;
import pathtracing.bdf.BDF;

public class Dielectric extends PhysicallyBasedMaterial {

    private final Color reflectance;
    private final double roughness;
    private final boolean transmissive;
    private final double ior;

    public Dielectric(Color reflectance, double roughness, boolean transmissive, double ior) {
        this.reflectance = reflectance;
        this.roughness = roughness;
        this.transmissive = transmissive;
        this.ior = ior;
    }

    private Color schlickFresnel(double cosTheta) {
        return reflectance.lerp(Color.WHITE, Math.pow(1.0 - cosTheta, 5.0));
    }

    @Override
    public Color surfaceColor(Vector normal, Vector incident, Vector intersection, Pathtracer pathtracer, int depth) {
        var cosTheta = Math.abs(incident.dot(normal));

        var schlick = schlickFresnel(cosTheta).scale(1.0 - roughness);

        var reflectionRay = new Ray(intersection, BDF.sampleBRDF(normal, incident, roughness), 1e-3, 1e3);
        var reflectedColor = pathtracer.traceDirect(reflectionRay, depth);

        //if (transmissive) {
        //    var refractionRay = new Ray(intersection, BDF.sampleBTDF(normal, incident, roughness, ior), 1e-3, 1e3);
        //    var refractionColor = reflectance.mul(pathtracer.traceDirect(refractionRay, depth));

         //   return refractionColor.lerp(reflectedColor, schlick);
        //} else {
            var diffuseRay = new Ray(intersection, BDF.sampleBRDF(normal, incident, 1.0), 1e-3, 1e3);
            var diffuseColor = reflectance.mul(pathtracer.traceDirect(diffuseRay, depth));

            return diffuseColor.lerp(reflectedColor, schlick);
       // }
    }
}
