#version 330 core

layout (location = 0) out vec4 FragColor;
layout (location = 1) out vec4 BrightColor;  

uniform float t;
uniform float light_intensity;

in vec3 LightPosition_worldspace;
in vec3 Position_worldspace;
in vec3 EyeDirection_worldspace;
in vec3 LightDirection_worldspace;
in vec3 Normal_worldspace;
in vec3 Color;

vec3 filmicToneMapping(vec3 color)
{
    color = max(vec3(0.), color - vec3(0.004));
    color = (color * (6.2 * color + .5)) / (color * (6.2 * color + 1.7) + 0.06);
    return color;
}

vec3 reinhardToneMapping(vec3 color){
    return color / (color + vec3(1.0));
}

vec3 gamma(vec3 c) {
    return pow(c, vec3(1.0/2.2));
}

void main() {

    vec3 n = normalize( Normal_worldspace );
    //vec3 n = normalize(vec3(1.2, -2.4, 4.1));
    vec3 l = normalize( LightDirection_worldspace );
    vec4 objectColor = vec4(Color,1);
    vec4 ambientcolor = vec4(1,1,1,1);
    vec4 diffusecolor = vec4(1,1,1,1);
    vec4 specularcolor = vec4(1,1,1,1);
    
    //float intensity = (0.1 * sin(3*t) + 0.3);
    
    float ambient_weight = 0.01;
    vec4 ambient = ambient_weight * ambientcolor;
    
    vec4 diffuse = max(dot(n,l),0.0) * diffusecolor;
    float specular_weight = 5;
    vec3 viewdir = normalize(EyeDirection_worldspace);  
    vec3 reflectdir = reflect(-l,n);
    float spec = pow(max(dot(viewdir, reflectdir), 0.0), 5);
    vec4 specular = specular_weight * spec * specularcolor;
    //vec4 specular = vec4(spec,spec,spec,1) * specularcolor;
    
    float d = length(Position_worldspace - LightPosition_worldspace);
    //FragColor = vec4(gamma(reinhardToneMapping(vec3((ambient + diffuse + specular) * objectColor / (0.001 * d*d)))),1); // Output. Color adjustment later?
    FragColor = vec4(vec3(light_intensity * (ambient + specular + diffuse) * objectColor / (0.001 * d*d)),1); // Output. Color adjustment later?
    
    // check whether fragment output is higher than threshold, if so output as brightness color
    float brightness = dot(FragColor.rgb, vec3(1.0, 1.0, 1.0));
    float threshold = 1.0;
    if(brightness > threshold){
        BrightColor = vec4(FragColor.rgb, 1.0);
    }
    else{
        BrightColor = vec4(exp(5.0*(brightness- threshold)) * FragColor.rgb, 1);
        //BrightColor = vec4(0,0,0,1);
    }

}

