#version 430 core

in layout(location = 1) vec4 fragCoordinate;
in layout(location = 2) vec2 texCoord;
in layout(location = 3) mat3 TBN;

uniform layout(location = 10) vec3 lightPosition;
uniform layout(binding = 2) sampler2D diffuseTexture;
uniform layout(binding = 3) sampler2D normalMap;

const vec3 cameraLocation = vec3(0, 0, 0);

out vec4 color;

void main()
{
    vec3 normalMapNormal = texture(normalMap, texCoord).rgb;
    normalMapNormal = normalize(TBN * normalize(normalMapNormal * 2.0 - 1.0));

    float distanceToLightSource = length(lightPosition - vec3(fragCoordinate));
    float attenuationFactor = 1.0 / (0.02 * distanceToLightSource);

    vec3 normalisedNormal = normalMapNormal; //normalize(normal);
    vec3 surfaceToLightVector = normalize(lightPosition - vec3(fragCoordinate));

    float diffuse = max(dot(normalisedNormal, surfaceToLightVector) * attenuationFactor, 0);
    //vec4 diffuseColour = vec4(diffuse, diffuse, diffuse, 1.0);
    vec4 diffuseColour = texture(diffuseTexture, texCoord);
    diffuseColour.xyz *= diffuse;
    diffuseColour *= vec4(0.6, 0.6, 0.6, 1.0);

    vec3 surfaceToEyeVector = normalize(cameraLocation - vec3(fragCoordinate));
    float specular = pow(max(dot(surfaceToEyeVector, reflect(-surfaceToLightVector, normalisedNormal)), 0), 64);
    vec4 specularColour = specular * attenuationFactor * vec4(0.2, 0.2, 0.2, 1.0);

    color = diffuseColour + specularColour;
    //color = vec4(0.5 * normalMapNormal + 0.5, 1.0);
    //color.x = 0;
    //color.y = 0;
}
